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

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