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

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