source: GTP/trunk/App/Demos/Vis/HillyTerrain/OGRE/TestCullingTerrainApplication.cpp @ 2501

Revision 2501, 23.6 KB checked in by mattausch, 17 years ago (diff)
Line 
1#include <OgreNoMemoryMacros.h>
2#include <CEGUI/CEGUI.h>
3#include <../CEGUIRenderer/include/OgreCEGUIRenderer.h>
4#include <../CEGUIRenderer/include/OgreCEGUIResourceProvider.h>
5#include <../CEGUIRenderer/include/OgreCEGUITexture.h>
6#include <OgreMemoryMacros.h>
7#include <OgreIteratorWrappers.h>
8#include <Ogre.h>
9#include "TestCullingTerrainApplication.h"
10#include "TerrainFrameListener.h"
11
12#if COLLADA
13#include "OgreColladaPrerequisites.h"
14#include "OgreColladaDocument.h"
15#include "OgreColladaScene.h"
16#endif
17
18#include "IVReader.h"
19
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22
23const static bool USE_STATIC_GEOMETRY = false;
24bool TestCullingTerrainApplication::msShowHillyTerrain = false;
25
26
27
28/*************************************************************/
29/*                EntityState implementation                 */
30/*************************************************************/
31
32
33Vector3 EntityState::msMinPos = Vector3::ZERO;
34Vector3 EntityState::msMaxPos = Vector3::ZERO;
35
36EntityState::EntityState(Entity *ent, State entityState, Real speed):
37mEntity(ent), mState(entityState), mAnimationSpeed(speed)
38{
39        switch(entityState)
40        {
41        case MOVING:
42                mAnimationState = mEntity->getAnimationState("Walk");
43                break;
44        case WAITING:
45                mAnimationState = mEntity->getAnimationState("Idle");
46                break;
47        case STOP:
48                mAnimationState = NULL;
49                break;
50        default:
51                break;
52        }
53        // enable animation state
54        if (mAnimationState)
55        {
56                mAnimationState->setLoop(true);
57                mAnimationState->setEnabled(true);
58        }
59
60        mTimeElapsed = Math::RangeRandom(1, 5);
61}
62//-----------------------------------------------------------------------
63EntityState::~EntityState()
64{
65        mAnimationState = NULL;
66        mEntity = NULL;
67}
68//-----------------------------------------------------------------------
69Entity *EntityState::GetEntity()
70{
71        return mEntity;
72}
73//-----------------------------------------------------------------------
74EntityState::State EntityState::GetState()
75{
76        return mState;
77}
78//-----------------------------------------------------------------------
79void EntityState::update(Real timeSinceLastFrame)
80{
81        mTimeElapsed -= timeSinceLastFrame * mAnimationSpeed;
82
83        if (!mEntity || !mAnimationState)
84                return;
85       
86        if (mState == MOVING) // toggle between moving (longer) and waiting (short)
87        {
88                SceneNode *parent = mEntity->getParentSceneNode();
89               
90                if (!parent)
91                        return;
92
93                if (mTimeElapsed <= 0) // toggle animation state
94                {
95                        if (mAnimationState->getAnimationName() == "Idle")
96                        {
97                                SetAnimationState("Walk", true);
98                               
99                                mTimeElapsed = walk_duration; // walk for mTimeElapsed units
100
101                                // choose random rotation
102                                Radian rnd = Radian(Math::UnitRandom() * Math::PI * rotate_factor);
103
104                                //mEntity->getParentSceneNode()->rotate();
105                                parent->yaw(rnd);                                               
106                        }
107                        else
108                        {
109                                SetAnimationState("Idle", true);
110                                mTimeElapsed = wait_duration; // wait for mTimeElapsed seconds
111                        }
112                }
113
114                if (mAnimationState->getAnimationName() == "Walk") // move forward
115                {
116                        // store old position, just in case we get out of bounds
117                        Vector3 oldPos = parent->getPosition();
118                        parent->translate(parent->getLocalAxes(), Vector3(move_factor * mAnimationSpeed, 0, 0));
119
120                        // HACK: if out of bounds => reset to old position and set animationstate to idle
121                        if (OutOfBounds(parent))
122                        {
123                                parent->setPosition(oldPos);
124                                SetAnimationState("Idle", true);
125                               
126                                mTimeElapsed = wait_duration;
127                        }
128                }
129        }
130               
131        // add time to drive animation
132        mAnimationState->addTime(timeSinceLastFrame * mAnimationSpeed);
133}
134//-----------------------------------------------------------------------
135void EntityState::SetAnimationState(String stateStr, bool loop)
136{
137        if (!mEntity)
138                return;
139
140        mAnimationState = mEntity->getAnimationState(stateStr);
141        mAnimationState->setLoop(loop);
142        mAnimationState->setEnabled(true);
143}
144//-----------------------------------------------------------------------
145bool EntityState::OutOfBounds(SceneNode *node)
146{
147        Vector3 pos = node->getPosition();
148
149        if ((pos > msMinPos) && (pos < msMaxPos))
150                return false;
151
152        return true;
153}
154
155
156
157/********************************************************************/
158/*            TestCullingTerrainApplication implementation          */
159/********************************************************************/
160
161
162TestCullingTerrainApplication::TestCullingTerrainApplication():
163mTerrainContentGenerator(NULL),
164mRayQueryExecutor(NULL),
165mIVReader(NULL),
166mFilename("terrain"),
167mViewCellsFilename(""),
168mAlgorithm(GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING)
169{
170}
171//-------------------------------------------------------------------------
172void TestCullingTerrainApplication::loadConfig(const String& filename)
173{
174        // Set up the options
175        ConfigFile config;
176        String val;
177
178        config.load(filename);
179
180        std::stringstream d; d << "reading the config file from: " << filename;
181        LogManager::getSingleton().logMessage(d.str());
182
183        val = config.getSetting("Scene");
184
185    if (!val.empty())
186        {
187                 mFilename = val.c_str();
188                 d << "\nloading scene from file: " << mFilename;
189                 LogManager::getSingleton().logMessage(d.str());
190        }
191}
192//-----------------------------------------------------------------------
193TestCullingTerrainApplication::~TestCullingTerrainApplication()
194{
195        OGRE_DELETE(mTerrainContentGenerator);
196        OGRE_DELETE(mRayQueryExecutor);
197        OGRE_DELETE(mIVReader);
198
199        deleteEntityStates();   
200}
201//-----------------------------------------------------------------------
202void TestCullingTerrainApplication::deleteEntityStates()
203{
204        for (int i = 0; i < (int)mEntityStates.size(); ++i)
205        {
206                OGRE_DELETE(mEntityStates[i]);
207        }
208
209        mEntityStates.clear();
210}
211//-----------------------------------------------------------------------
212void TestCullingTerrainApplication::createCamera()
213{
214        // create the camera
215        mCamera = mSceneMgr->createCamera("PlayerCam");
216       
217        /** set a nice viewpoint
218        *       we use a camera node here and apply all transformations on it instead
219        *       of applying all transformations directly to the camera
220        *       because then the camera is displayed correctly in the visualization
221        */
222        // hack: vienna view point
223        Vector3 viewPoint(830, 300, -540);
224       
225        mCamNode = mSceneMgr->getRootSceneNode()->
226                createChildSceneNode("CamNode1", viewPoint);
227       
228        mCamNode->setOrientation(Quaternion(-0.3486, 0.0122, 0.9365, 0.0329));
229        mCamNode->attachObject(mCamera);
230       
231
232        ///////////////////
233        //-- create visualization camera
234
235        mVizCamera = mSceneMgr->createCamera("VizCam");
236        mVizCamera->setPosition(mCamNode->getPosition());
237
238        mVizCamera->setNearClipDistance(1);
239        mCamera->setNearClipDistance(1);
240
241        // infinite far plane?
242        if (mRoot->getRenderSystem()->getCapabilities()->hasCapability(RSC_INFINITE_FAR_PLANE))
243        {
244                mVizCamera->setFarClipDistance(0);
245                mCamera->setFarClipDistance(0);
246        }
247        else
248        {
249                 mVizCamera->setFarClipDistance(20000);
250                 mCamera->setFarClipDistance(20000);
251        }       
252}
253
254//-----------------------------------------------------------------------
255bool TestCullingTerrainApplication::setup()
256{
257        bool carryOn = ExampleApplication::setup();
258
259        if (carryOn)
260                createRenderTargetListener();
261
262        return carryOn;
263}
264//-----------------------------------------------------------------------
265void TestCullingTerrainApplication::createRenderTargetListener()
266{
267        mWindow->addListener(new VisualizationRenderTargetListener(mSceneMgr));
268}
269//-----------------------------------------------------------------------
270bool TestCullingTerrainApplication::LoadSceneCollada(const String &filename,
271                                                                                                         SceneNode *root,
272                                                                                                         const int index)
273{
274#if COLLADA
275        // Collada
276        ColladaDocument *daeDoc = new ColladaDocument(mSceneMgr);
277
278        String daeName = filename;
279        //if (daeName.empty())
280        //      daeName = "City_1500.dae";
281
282        // default directory
283        //daeName.insert(0, "../../media/models/collada/City");
284        LogManager::getSingleton().logMessage("ColladaDocument - import started");
285
286        // full import
287        if (daeDoc->doImport(daeName))
288        {
289                LogManager::getSingleton().logMessage("loading collada");
290                /**
291                 * build up scene
292                 * if you only want a specific part of the scene graph, you must fetch a scene node
293                 * by its unique node name and give it as parameter
294                 * e.g.
295                 * ColladaSceneNode *box = mScene->getNode("Box2");
296                 * if (box != NULL) box->createOgreInstance(NULL);
297                 */
298                daeDoc->getScene()->createOgreInstance(NULL);
299
300                // everything is loaded, we do not need the collada document anymore
301                delete daeDoc;
302
303                return true;
304        }
305        else
306        {
307                LogManager::getSingleton().logMessage("ColladaDocument - import failed");
308                return false;
309        }
310#endif
311        return true;
312}
313//-----------------------------------------------------------------------
314bool TestCullingTerrainApplication::LoadSceneIV(const String &filename,
315                                                                                                SceneNode *root,
316                                                                                                const int index)
317{
318        mIVReader = new IVReader();
319
320        Timer *timer = PlatformManager::getSingleton().createTimer();
321        timer->reset();
322
323        if (1)
324        {
325                std::string logFilename = "IVLog" + Ogre::StringConverter().toString(index) + ".log";
326               
327                Log *log = LogManager::getSingleton().createLog(logFilename);
328                mIVReader->setLog(log);
329        }
330       
331        //viennaNode->translate(Vector3(-300, -300, 0));
332
333        if (mIVReader->loadFile(filename.c_str()))
334        {
335                SceneNode *node = root->createChildSceneNode("IVSceneNode" + index);
336
337                mIVReader->buildTree(mSceneMgr, node);
338               
339                mIVReader->collapse();
340                OGRE_DELETE(mIVReader);
341
342                std::stringstream d;
343                d << "loaded " << filename << " in " << timer->getMilliseconds() * 1e-3 << " secs";
344                LogManager::getSingleton().logMessage(d.str());
345               
346                PlatformManager::getSingleton().destroyTimer(timer);
347
348                //-- bake into static geometry
349                if (USE_STATIC_GEOMETRY)
350                {
351                        BakeSceneIntoStaticGeometry("staticVienna", "Vienna");
352                }
353       
354                return true;
355        }
356
357        return false;
358}
359//--------------------------------------------------------
360void TestCullingTerrainApplication::BakeSceneIntoStaticGeometry(const String &staticGeomName,
361                                                                                                                                const String &nodeName)
362{
363#if OGRE_103
364        // note: different static geom for roofs, roads, ..., becazse they have same material
365        StaticGeometry *staticGeom = mSceneMgr->createStaticGeometry(staticGeomName);
366
367        // note: looping over entities here. why does scene node not work?
368        SceneManager::EntityIterator it = mSceneMgr->getEntityIterator();
369        while (it.hasMoreElements())
370        {
371                Entity *ent = it.getNext();
372                ent->setVisible(false);
373                staticGeom->addEntity(ent, ent->getParentSceneNode()->getPosition());
374        }
375
376        staticGeom->setRegionDimensions(Vector3(100,100,100));
377        staticGeom->build();
378
379        // cleanup node
380        //wallsNode->detachAllObjects();
381       
382        //roofsNode->detachAllObjects();
383        //roadsNode->detachAllObjects();
384        //planeNode->detachAllObjects();
385       
386        //viennaNode->removeChild("Walls");
387        mSceneMgr->destroySceneNode(nodeName);
388#endif
389}
390//--------------------------------------------------------
391void TestCullingTerrainApplication::createScene()
392{
393        /////////
394        //-- load parameters & scene
395        //loadConfig("terrainCulling.cfg");
396       
397        /////////////////////////////////////
398
399        // Set ambient light
400        mAmbientLight = ColourValue(0.5, 0.5, 0.5);
401        mSceneMgr->setAmbientLight(mAmbientLight);
402       
403        //-- create light
404        mSunLight = mSceneMgr->createLight("SunLight");
405        mSunLight->setType(Light::LT_DIRECTIONAL);
406        //mSunLight->setType(Light::LT_SPOTLIGHT);
407        //mSunLight->setSpotlightRange(Degree(30), Degree(50));
408
409    mSunLight->setPosition(707, 2000, 500);
410        mSunLight->setCastShadows(true);
411
412        // set light angle not too small over the surface,
413        // otherwise shadows textures will be broken
414        Vector3 dir(0.5, 1, 0.5);
415        dir.normalise();
416        mSunLight->setDirection(dir);
417        //mSunLight->setDirection(Vector3::NEGATIVE_UNIT_Y);
418        mSunLight->setDiffuseColour(1, 1, 1);
419        mSunLight->setSpecularColour(1, 1, 1);
420
421        //-- Fog
422
423        // NB it's VERY important to set this before calling setWorldGeometry
424        // because the vertex program picked will be different
425        ColourValue fadeColour(0.93, 0.86, 0.76);
426        mWindow->getViewport(0)->setBackgroundColour(fadeColour);
427        //mSceneMgr->setFog(FOG_LINEAR, fadeColour, .001, 500, 1000);
428       
429        // Create a skybox
430        mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 50000, true);
431       
432        // terrain creation
433        std::string terrain_cfg("terrainCulling.cfg");
434       
435        mSceneMgr->setWorldGeometry(terrain_cfg);
436
437        // was terrain loaded?
438        mSceneMgr->getOption("ShowTerrain", &msShowHillyTerrain);
439               
440        // hack view point for terrain
441        if (msShowHillyTerrain)
442        {
443                Vector3 viewPoint(707, 5000, 528);
444                mCamNode->setPosition(viewPoint);
445        }
446
447       
448        //-- CEGUI setup
449        setupGui();
450
451        // Warning: In GL since we can't go higher than the window res
452        mSceneMgr->setShadowTextureSettings(1024, 2);
453        mSceneMgr->setShadowColour(ColourValue(0.5, 0.5, 0.5));
454
455
456        //////////////
457        //-- terrain content setup
458
459        // HACK: necessary to call once here for terrain initialisation
460        mSceneMgr->_renderScene(mCamera, mWindow->getViewport(0), true);
461
462        // ray query executor: needed to clamp to terrain
463        mRayQueryExecutor = new RayQueryExecutor(mSceneMgr);
464
465        mTerrainMinPos = EntityState::msMinPos = Vector3(0, 0, 0);
466        mTerrainMaxPos = EntityState::msMaxPos = Vector3(5000, 5000, 5000);
467
468        mTerrainContentGenerator = new TerrainContentGenerator(mSceneMgr);
469               
470        // if no objects in file, we generate new objects
471        if (msShowHillyTerrain && !mTerrainContentGenerator->LoadObjects("objects.out"))
472        {
473                // the objects are generated randomly distributed over the terrain
474                if (1) generateScene(500, 0); // create robots
475                if (0) generateScene(300, 1); // create ninjas
476                if (0) generateScene(1000, 2); // create trees
477        }
478
479        int maxDepth = 30;
480       
481        mSceneMgr->setOption("BiHierarchyMaxDepth", &maxDepth);
482       
483        int mode = 1;
484       
485        mSceneMgr->setOption("EnhancedVisibility", &mode);
486        mSceneMgr->setOption("RebuildBiHierarchy", NULL);
487        mSceneMgr->setOption("RebuildKdTree", NULL);
488}
489//-----------------------------------------------------------------------
490void  TestCullingTerrainApplication::generateScene(int num, int objectType)
491{
492        const float val = TerrainFrameListener::msObjectScales[objectType];
493        Vector3 scale(val, val, val);
494        const float maxHeight = 75;
495       
496        // In order to provide much occlusion,
497        // height is restricted to maxHeight => no objects are created on peaks
498        mTerrainContentGenerator->SetMinPos(Vector3(mTerrainMinPos));
499        mTerrainContentGenerator->SetMaxPos(Vector3(mTerrainMaxPos.x, maxHeight, mTerrainMaxPos.z));
500       
501        mTerrainContentGenerator->SetScale(scale);
502        mTerrainContentGenerator->SetOffset(TerrainFrameListener::msObjectTerrainOffsets[objectType]);
503        mTerrainContentGenerator->GenerateScene(num, TerrainFrameListener::msObjectCaptions[objectType]);
504
505        if (objectType != 0) // from our objects, only robot has animation phases
506                return;
507
508        EntityList *entList = mTerrainContentGenerator->GetGeneratedEntities();
509
510        /////////////
511        //-- add animation state for new robots (located at the end of the list)
512       
513        for (size_t i = entList->size() - (unsigned int)num; i < entList->size(); ++ i)
514        {
515                mEntityStates.push_back(new EntityState((*entList)[i],
516                        EntityState::WAITING, Math::RangeRandom(0.5, 1.5)));
517        }
518
519        // release limitations on height => it is possible for the user to put single
520        // objects on peaks of the terrain (will be only few, not relevant for occlusion)
521        mTerrainContentGenerator->SetMaxPos(mTerrainMaxPos);
522}
523//-----------------------------------------------------------------------
524void TestCullingTerrainApplication::updateAnimations(Real timeSinceLastFrame)
525{
526        for (int i = 0; i < (int)mEntityStates.size(); ++i)
527        {
528                SceneNode *sn = mEntityStates[i]->GetEntity()->getParentSceneNode();
529
530                mEntityStates[i]->update(timeSinceLastFrame);
531
532                if (mEntityStates[i]->GetState() == EntityState::MOVING)
533                {
534                        Clamp2Terrain(sn, 0); //sn->setNodeVisible(false);
535                }
536        }
537}
538//-----------------------------------------------------------------------
539EntityStates  &TestCullingTerrainApplication::getEntityStates()
540{
541        return mEntityStates;
542}
543//-----------------------------------------------------------------------
544void TestCullingTerrainApplication::setupGui()
545{
546#if OGRE103
547         mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY,
548                 false, 3000, ST_EXTERIOR_CLOSE);
549#else
550          mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY,
551                 false, 3000, mSceneMgr);
552#endif
553     mGUISystem = new CEGUI::System(mGUIRenderer);
554
555         // Mouse
556     CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"TaharezLook.scheme");
557     CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseArrow");
558         mGUISystem->setDefaultMouseCursor((CEGUI::utf8*)"TaharezLook",
559                                                                           (CEGUI::utf8*)"MouseArrow");
560
561         CEGUI::MouseCursor::getSingleton().hide();
562}
563//-----------------------------------------------------------------------
564void TestCullingTerrainApplication::createFrameListener()
565{
566        mTerrainFrameListener =
567                new TerrainFrameListener(mWindow,
568                                                                 mCamera,
569                                                                 mSceneMgr,
570                                                                 mGUIRenderer,
571                                                                 mTerrainContentGenerator,
572                                                                 mVizCamera,
573                                                                 mCamNode,
574                                                                 mSunLight,
575                                                                 this);
576
577        mTerrainFrameListener->setPriority(10);
578       
579        mRoot->addFrameListener(mTerrainFrameListener);
580}
581//-----------------------------------------------------------------------
582void TestCullingTerrainApplication::chooseSceneManager()
583{
584#ifdef OGRE_103
585        if (msShowHillyTerrain)
586        {
587                // Terrain scene manager
588                mSceneMgr = mRoot->getSceneManager(ST_EXTERIOR_CLOSE);
589        }
590        else
591        {       // octree scene manager
592                mSceneMgr = mRoot->getSceneManager(ST_GENERIC);
593        }
594#else
595
596        mSceneMgr = mRoot->createSceneManager("OcclusionCullingSceneManager");
597       
598        //mSceneMgr = mRoot->createSceneManager("TerrainSceneManager");
599        //mSceneMgr = mRoot->createSceneManager("OctreeSceneManager");
600        //mSceneMgr = mRoot->createSceneManager("BiHierarchySceneManager");
601        //mSceneMgr = mRoot->createSceneManager("BiTreeTerrainSceneManager");
602       
603        bool useEnhancedVisibility = true;
604        mSceneMgr->setOption("EnhancedVisibility", &useEnhancedVisibility);
605#endif
606}
607//-----------------------------------------------------------------------
608bool TestCullingTerrainApplication::Clamp2Terrain(SceneNode *node, int terrainOffs)
609{
610        // clamp scene node to terrain
611        Vector3 pos = node->getPosition();
612        Vector3 queryResult;
613
614        if (mRayQueryExecutor->executeRayQuery(&queryResult,
615                        Vector3(pos.x, MAX_HEIGHT, pos.z), Vector3::NEGATIVE_UNIT_Y))
616        {
617        node->setPosition(pos.x, queryResult.y + terrainOffs, pos.z);
618                return true;
619        }
620
621        return false;
622}
623
624//-----------------------------------------------------------------------
625bool TestCullingTerrainApplication::Clamp2FloorPlane(const float dist)
626{
627    // clamp to floor plane
628        RaySceneQuery *raySceneQuery = mSceneMgr->createRayQuery(
629                Ray(mCamNode->getPosition(), Vector3::NEGATIVE_UNIT_Y));
630
631        RaySceneQueryResult& qryResult = raySceneQuery->execute();
632   
633        RaySceneQueryResult::iterator rit = qryResult.begin();
634        bool success = false;
635       
636        float yVal = 0;
637        float minVal = 999999999999;
638
639        // find next valid intersection
640        while (rit != qryResult.end() && rit->movable)
641        {
642                // camera is not a real world object
643                if (rit->movable->getName() != "PlayerCam")
644                {
645                        // get the next intersection with a movable object
646                        yVal = rit->movable->getWorldBoundingBox().getCenter().y;
647
648                        if (yVal < minVal)
649                                minVal = yVal;
650
651                        success = true;
652                }
653
654                ++ rit;
655        }
656
657        // place player on the ground object
658        if (success)
659        {
660                mCamNode->setPosition(mCamNode->getPosition().x,
661                                                          minVal + dist,
662                                                          mCamNode->getPosition().z);
663        }
664
665        OGRE_DELETE(raySceneQuery);
666        return success;
667}
668
669//-----------------------------------------------------------------------
670// splits strings containing multiple file names
671static int SplitFilenames(const std::string str, std::vector<std::string> &filenames)
672{
673        int pos = 0;
674
675        while(1)
676        {
677                int npos = (int)str.find(';', pos);
678               
679                if (npos < 0 || npos - pos < 1)
680                        break;
681                filenames.push_back(std::string(str, pos, npos - pos));
682                pos = npos + 1;
683        }
684       
685        filenames.push_back(std::string(str, pos, str.size() - pos));
686        return (int)filenames.size();
687}
688//-----------------------------------------------------------------------
689bool TestCullingTerrainApplication::LoadScene(const String &filename)
690{
691        using namespace std;
692        // use leaf nodes of the original spatial hierarchy as occludees
693        vector<string> filenames;
694        int files = SplitFilenames(filename, filenames);
695       
696        std::stringstream d;
697        d << "number of input files: " << files << "\n";
698        LogManager::getSingleton().logMessage(d.str());
699
700        bool result = false;
701        vector<string>::const_iterator fit, fit_end = filenames.end();
702        int i = 0;
703
704        for (fit = filenames.begin(); fit != fit_end; ++ fit, ++ i)
705        {
706                const string fn = *fit;
707
708                if (strstr(fn.c_str(), ".iv") || strstr(fn.c_str(), ".wrl"))
709                {
710                        // load iv files
711                        if (!LoadSceneIV(fn, mSceneMgr->getRootSceneNode(), i))
712                        {
713                                // terrain hack
714                                //msShowHillyTerrain = true;
715                                LogManager::getSingleton().logMessage("error loading scene => load terrain");
716                        }
717                }
718                else if (strstr(filename.c_str(), ".dae"))
719                {
720                        // load collada files
721                        LoadSceneCollada(fn, mSceneMgr->getRootSceneNode(), i);         
722                }
723                else //if (filename == "terrain")
724                {
725                        // terrain hack
726                        msShowHillyTerrain = true;
727                        LogManager::getSingleton().logMessage("loading terrain");
728                }
729       
730                result = true;
731        }
732       
733        return result;
734}
735//-----------------------------------------------------------------------
736bool TestCullingTerrainApplication::LoadViewCells(const String &filename)
737{
738        // if not already loaded,
739        // the scene manager will load the view cells
740        return mSceneMgr->setOption("UseViewCells", filename.c_str());
741}
742
743
744
745/**********************************************************************/
746/*           VisualizationRenderTargetListener implementation         */
747/**********************************************************************/
748
749//-----------------------------------------------------------------------
750VisualizationRenderTargetListener::VisualizationRenderTargetListener(SceneManager *sceneMgr)
751:RenderTargetListener(), mSceneMgr(sceneMgr)
752{
753}
754//-----------------------------------------------------------------------
755void VisualizationRenderTargetListener::preViewportUpdate(const RenderTargetViewportEvent &evt)
756{
757        // visualization viewport
758        const bool showViz = evt.source->getZOrder() == VIZ_VIEWPORT_Z_ORDER;
759        const bool nShowViz = !showViz;
760
761        mSavedShadowTechnique = mSceneMgr->getShadowTechnique();
762        mSavedAmbientLight = mSceneMgr->getAmbientLight();
763
764        // -- ambient light must be full for visualization, shadows disabled
765    if (showViz)
766        {
767                mSceneMgr->setAmbientLight(ColourValue(1, 1, 1));
768                mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
769        }
770       
771    mSceneMgr->setOption("PrepareVisualization", &showViz);
772        mSceneMgr->setOption("SkyBoxEnabled", &nShowViz);
773       
774        RenderTargetListener::preViewportUpdate(evt);
775}
776//-----------------------------------------------------------------------
777void VisualizationRenderTargetListener::postRenderTargetUpdate(const RenderTargetEvent &evt)
778{
779        // reset values
780        mSceneMgr->setShadowTechnique(mSavedShadowTechnique);
781        mSceneMgr->setAmbientLight(mSavedAmbientLight);
782       
783        RenderTargetListener::postRenderTargetUpdate(evt);
784}
785//-----------------------------------------------------------------------
786INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
787{
788    // Create application object
789    TestCullingTerrainApplication app;
790
791        try
792        {
793        app.go();
794    }
795        catch( Ogre::Exception& e )
796        {
797        MessageBox( NULL, e.getFullDescription().c_str(),
798                        "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
799    }   
800
801    return 0;
802}
Note: See TracBrowser for help on using the repository browser.