Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/improvements/src/story_entities/game_world.cc @ 10300

Last change on this file since 10300 was 10300, checked in by snellen, 17 years ago

update

File size: 18.7 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Patrick Boenzli
13   co-programmer: Christian Meyer
14   co-programmer: Benjamin Grauer
15*/
16
17#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD
18
19#include "game_world.h"
20#include "game_world_data.h"
21
22#include "state.h"
23
24#include "util/loading/game_loader.h"
25#include "util/timer.h"
26
27#include "player.h"
28#include "camera.h"
29#include "environment.h"
30#include "terrain.h"
31#include "test_entity.h"
32#include "terrain.h"
33#include "playable.h"
34#include "environments/mapped_water.h"
35
36#include "light.h"
37
38#include "util/loading/factory.h"
39#include "util/loading/load_param_xml.h"
40#include "loading/fast_factory.h"
41#include "shell_command.h"
42
43#include "graphics_engine.h"
44#include "weather_effects/atmospheric_engine.h"
45#include "event_handler.h"
46#include "sound_engine.h"
47#include "cd_engine.h"
48#include "network_manager.h"
49#include "physics_engine.h"
50
51#include "glmenu_imagescreen.h"
52#include "shell.h"
53
54#include "ogg_player.h"
55#include "shader.h"
56
57#include "animation_player.h"
58
59#include "game_rules.h"
60
61#include "script_class.h"
62ObjectListDefinition(GameWorld);
63CREATE_SCRIPTABLE_CLASS(GameWorld,
64                        addMethod("setPlaymode", Executor1<GameWorld, lua_State*,const std::string&>(&GameWorld::setPlaymode))
65                        ->addMethod("setSoundtrack", Executor1<GameWorld, lua_State*, const std::string&>(&GameWorld::setSoundtrack))
66                        ->addMethod("getStoryID", Executor0ret<StoryEntity, lua_State*, int>(&StoryEntity::getStoryID))
67                        ->addMethod("setNextStoryName", Executor1ret<StoryEntity, lua_State*, bool, const std::string&>(&StoryEntity::setNextStoryName))
68                        ->addMethod("stop", Executor0ret<GameWorld, lua_State*, bool>(&GameWorld::stop))
69                       );
70
71SHELL_COMMAND(speed, GameWorld, setSpeed) ->describe("set the Speed of the Level");
72SHELL_COMMAND(playmode, GameWorld, setPlaymode)
73->describe("Set the Playmode of the current Level")
74->completionPlugin(0, OrxShell::CompletorStringArray(Playable::playmodeNames, Playable::PlaymodeCount));
75
76SHELL_COMMAND(togglePNodeVisibility, GameWorld, togglePNodeVisibility);
77SHELL_COMMAND(showBVLevel, GameWorld, toggleBVVisibility);
78
79
80GameWorld::GameWorld()
81    : StoryEntity()
82{
83  this->registerObject(this, GameWorld::_objectList);
84  this->setName("Preloaded World - no name yet");
85
86  this->gameTime = 0.0f;
87  this->setSpeed(1.0f);
88  this->shell = NULL;
89
90  this->showPNodes = false;
91  this->showBV = false;
92  this->showBVLevel = 3;
93
94  this->dataXML = NULL;
95  this->gameRules = NULL;
96}
97
98/**
99 *  remove the GameWorld from memory
100 *
101 *  delete everything explicitly, that isn't contained in the parenting tree!
102 *  things contained in the tree are deleted automaticaly
103 */
104GameWorld::~GameWorld ()
105{
106  PRINTF(4)("Deleted GameWorld\n");
107
108}
109
110
111
112/**
113 * loads the parameters of a GameWorld from an XML-element
114 * @param root the XML-element to load from
115 */
116void GameWorld::loadParams(const TiXmlElement* root)
117{
118  StoryEntity::loadParams(root);
119
120  PRINTF(4)("Loaded GameWorld specific stuff\n");
121}
122
123
124/**
125 * this is executed just before load
126 *
127 * since the load function sometimes needs data, that has been initialized
128 * before the load and after the proceeding storyentity has finished
129*/
130ErrorMessage GameWorld::init()
131{
132  /* init the world interface */
133  this->shell = new OrxShell::Shell();
134
135  State::setCurrentStoryEntity(dynamic_cast<StoryEntity*>(this));
136  this->dataTank->init();
137
138  /* initialize some engines and graphical elements */
139  AnimationPlayer::getInstance();
140  PhysicsEngine::getInstance();
141  CREngine::getInstance();
142
143  State::setScriptManager(&this->scriptManager);
144
145  return ErrorMessage();
146}
147
148/**
149 *  loads the GameWorld by initializing all resources, and set their default values.
150 */
151ErrorMessage GameWorld::loadData()
152{
153  this->displayLoadScreen();  State::setScriptManager(&this->scriptManager);
154
155
156  PRINTF(4)("Loading the GameWorld\n");
157
158  PRINTF(3)("> Loading world: '%s'\n", getLoadFile().c_str());
159  //  TiXmlElement* element;
160  //  GameLoader* loader = GameLoader::getInstance();
161
162  if( getLoadFile().empty())
163  {
164    PRINTF(1)("GameWorld has no path specified for loading\n");
165    return (ErrorMessage(213,"Path not specified","GameWorld::load()"));
166  }
167
168  TiXmlDocument* XMLDoc = new TiXmlDocument( getLoadFile());
169  // load the xml world file for further loading
170  if( !XMLDoc->LoadFile())
171  {
172    PRINTF(1)("loading XML File: %s @ %s:l%d:c%d\n", XMLDoc->ErrorDesc(), this->getLoadFile().c_str(), XMLDoc->ErrorRow(), XMLDoc->ErrorCol());
173    delete XMLDoc;
174    return ErrorMessage(213,"XML File parsing error","GameWorld::load()");
175  }
176  // check basic validity
177  TiXmlElement* root = XMLDoc->RootElement();
178  assert( root != NULL);
179  if( root == NULL || root->Value() == NULL || strcmp( root->Value(), "WorldDataFile"))
180  {
181    // report an error
182    PRINTF(1)("Specified XML File is not an orxonox world data file (WorldDataFile element missing)\n");
183    delete XMLDoc;
184    return ErrorMessage(213,"Path not a WorldDataFile","GameWorld::load()");
185  }
186  /* the whole loading process for the GameWorld */
187  this->dataTank->loadData(root);
188  this->dataXML = (TiXmlElement*)root->Clone();
189
190  //remove this after finished testing !!!!
191  //Object* obj= new Object();
192  //obj->setName("Obj");
193  //Account* a = new Account();
194  //a->setName("a");
195  //Account *b = new Account(30);
196  //b->setName("b");
197
198
199  LoadParamXML(root, "ScriptManager", &this->scriptManager, ScriptManager, loadParams);
200
201  delete XMLDoc;
202  this->releaseLoadScreen();
203
204  return ErrorMessage();
205}
206
207
208/**
209 *  unload the data of this GameWorld
210 */
211ErrorMessage GameWorld::unloadData()
212{
213
214  PRINTF(3)("GameWorld::~GameWorld() - unloading the current GameWorld\n");
215  this->scriptManager.flush();
216
217  delete this->shell;
218
219  this->dataTank->unloadData();
220
221  this->shell = NULL;
222  delete AnimationPlayer::getInstance();
223  delete PhysicsEngine::getInstance();
224  delete CREngine::getInstance();
225
226  State::setCurrentStoryEntity(NULL);
227  if (this->dataXML)
228    delete this->dataXML;
229
230  return ErrorMessage();
231}
232
233
234void GameWorld::setSoundtrack(const std::string& soundTrack)
235{
236  if (this->dataTank != NULL)
237  {
238    this->dataTank->setSoundTrack(soundTrack);
239    this->dataTank->music->play();
240  }
241}
242
243
244/**
245 *  starts the GameWorld
246 */
247bool GameWorld::start()
248{
249  this->bPaused = false;
250  this->bRunning = true;
251  State::setScriptManager(&this->scriptManager); //make sure we have the right script manager
252  this->run();
253
254  return true;
255}
256
257
258/**
259 *  stops the world.
260 */
261bool GameWorld::stop()
262{
263  PRINTF(3)("GameWorld::stop() - got stop signal\n");
264  State::setScriptManager(NULL);
265  return (this->bRunning = false);
266}
267
268
269/**
270 *  pauses the game
271 */
272bool GameWorld::pause()
273{
274  return (this->bPaused = true);
275}
276
277
278/**
279 *  ends the pause Phase
280 */
281bool GameWorld::resume()
282{
283  return(this->bPaused = false);
284}
285
286
287/**
288 *  main loop of the world: executing all world relevant function
289 *
290 * in this loop we synchronize (if networked), handle input events, give the heart-beat to
291 * all other member-entities of the world (tick to player, enemies etc.), checking for
292 * collisions drawing everything to the screen.
293 */
294void GameWorld::run()
295{
296  PRINTF(3)("GameWorld::mainLoop() - Entering main loop\n");
297
298  // initialize Timing
299  this->cycle = 0;
300  for (unsigned int i = 0; i < TICK_SMOOTH_VALUE; i++)
301    this->frameTimes[i] = 0.01f;
302  this->dtS = 0.0f;
303  this->lastFrame = Timer::getNow();
304
305  if (this->dataTank->music != NULL)
306    this->dataTank->music->play();
307
308  PNode::getNullParent()->updateNode(0.01);
309  PNode::getNullParent()->updateNode(0.01);
310
311 
312  while( this->bRunning) /* @todo implement pause */
313  {
314    /* process intput */
315    this->handleInput ();
316    if( !this->bRunning)
317      break;
318
319    /* network synchronisation */
320    this->synchronize ();
321    /* process time */
322    this->tick ();
323
324
325    /* update the state */
326    //this->update (); /// LESS REDUNDANCY.
327    //      PNode::getNullParent()->updateNode(this->dtS);
328    PNode::getNullParent()->updateNode(this->dtS);
329
330    /* collision detection */
331    this->collisionDetection ();
332    /* collision reaction */
333    this->collisionReaction ();
334
335    /* check the game rules */
336    this->checkGameRules();
337
338    /* update the state */
339    this->update ();
340    /* draw everything */
341    this->display ();
342
343  }
344
345  PRINTF(4)("GameWorld::mainLoop() - Exiting the main loop\n");
346}
347
348
349void GameWorld::setPlaymode(Playable::Playmode playmode)
350{
351  if (this->dataTank->localPlayer &&
352      this->dataTank->localPlayer->getPlayable() &&
353      this->dataTank->localPlayer->getPlayable()->setPlaymode(playmode))
354  {
355    PRINTF(4)("Set Playmode to %d:%s\n", playmode, Playable::playmodeToString(playmode).c_str());
356  }
357  else
358  {
359    PRINTF(2)("Unable to set Playmode %d:'%s'\n", playmode, Playable::playmodeToString(playmode).c_str());
360  }
361}
362
363void GameWorld::setPlaymode(const std::string& playmode)
364{
365  this->setPlaymode(Playable::stringToPlaymode(playmode));
366}
367
368/**
369 *  synchronize local data with remote data
370*/
371void GameWorld::synchronize ()
372{}
373
374
375/**
376 *  run all input processing
377
378   the command node is the central input event dispatcher. the node uses the even-queue from
379   sdl and has its own event-passing-queue.
380*/
381void GameWorld::handleInput ()
382{
383  EventHandler::getInstance()->process();
384}
385
386
387/**
388 * @brief ticks a WorldEntity list
389 * @param entityList list of the WorldEntities
390 * @param dt time passed since last frame
391 */
392void GameWorld::tick(ObjectManager::EntityList entityList, float dt)
393{
394  ObjectManager::EntityList::iterator entity, next;
395  next = entityList.begin();
396  while (next != entityList.end())
397  {
398    entity = next++;
399    (*entity)->tick(dt);
400  }
401}
402
403
404/**
405 *  advance the timeline
406 *
407 * this calculates the time used to process one frame (with all input handling, drawing, etc)
408 * the time is mesured in ms and passed to all world-entities and other classes that need
409 * a heart-beat.
410 */
411void GameWorld::tick ()
412{
413  if( !this->bPaused)
414  {
415    // CALCULATE FRAMERATE
416    Uint32 frameTimesIndex;
417    Uint32 i;
418    double currentFrame = Timer::getNow();
419
420    if (currentFrame - this->lastFrame < .01)
421    {
422      SDL_Delay((int)(1000.0 * (0.01 - (currentFrame - lastFrame))));
423      currentFrame = Timer::getNow();
424    }
425
426
427    frameTimesIndex = this->cycle % TICK_SMOOTH_VALUE;
428    this->frameTimes[frameTimesIndex] = currentFrame - this->lastFrame;
429    this->lastFrame = currentFrame;
430    ++this->cycle;
431    this->dtS = 0.0;
432    for (i = 0; i < TICK_SMOOTH_VALUE; i++)
433      this->dtS += this->frameTimes[i];
434    this->dtS = this->dtS / TICK_SMOOTH_VALUE * speed;
435
436    // TICK everything
437    for (i = 0; i < this->dataTank->tickLists.size(); ++i)
438      this->tick(this->dataTank->objectManager->getEntityList(this->dataTank->tickLists[i]), this->dtS);
439
440    /* update tick the rest */
441    this->dataTank->localCamera->tick(this->dtS);
442    AnimationPlayer::getInstance()->tick(this->dtS);
443    PhysicsEngine::getInstance()->tick(this->dtS);
444
445    GraphicsEngine::getInstance()->tick(this->dtS);
446    AtmosphericEngine::getInstance()->tick(this->dtS);
447
448    if( likely(this->dataTank->gameRule != NULL))
449      this->dataTank->gameRule->tick(this->dtS);
450
451  }
452}
453
454
455/**
456 *  this function gives the world a consistant state
457 *
458 * after ticking (updating the world state) this will give a constistant
459 * state to the whole system.
460 */
461void GameWorld::update()
462{
463  PNode::getNullParent()->updateNode (this->dtS);
464  OrxSound::SoundEngine::getInstance()->update();
465
466  this->applyCameraSettings();
467  GraphicsEngine::getInstance()->update(this->dtS);
468}
469
470
471/**
472 * kicks the CDEngine to detect the collisions between the object groups in the world
473 */
474void GameWorld::collisionDetection()
475{
476  // object-object collision detection
477  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
478      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
479  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
480      this->dataTank->objectManager->getEntityList(OM_GROUP_00_PROJ));
481  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
482      this->dataTank->objectManager->getEntityList(OM_GROUP_00));
483
484  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
485      this->dataTank->objectManager->getEntityList(OM_GROUP_02));
486  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_02),
487      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
488
489
490  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
491      this->dataTank->objectManager->getEntityList(OM_COMMON));
492  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
493      this->dataTank->objectManager->getEntityList(OM_COMMON));
494
495  // ground collision detection: BSP Model
496  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_00));
497  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_01));
498}
499
500
501void GameWorld::collisionReaction()
502{
503  CREngine::getInstance()->handleCollisions();
504}
505
506
507/**
508 *  check the game rules: winning conditions, etc.
509 *
510 */
511void GameWorld::checkGameRules()
512{
513  if( this->gameRules)
514    this->gameRules->tick(this->dtS);
515}
516
517
518/**
519 *  render the current frame
520 *
521 * clear all buffers and draw the world
522 */
523void GameWorld::display ()
524{
525
526  // if this server is a dedicated server the game workd does not need to be drawn
527  if( !GraphicsEngine::getInstance()->isDedicated())
528  {
529    // render the reflection texture
530    this->renderPassReflection();
531    // redner the refraction texture
532    this->renderPassRefraction();
533  }
534  // render all
535  this->renderPassAll();
536
537  // flip buffers
538  GraphicsEngine::swapBuffers();
539}
540
541
542/**
543 * @brief draws all entities in the list drawList
544 * @param drawList the List of entities to draw.
545 */
546void GameWorld::drawEntityList(const ObjectManager::EntityList& drawList) const
547{
548  ObjectManager::EntityList::const_iterator entity;
549  for (entity = drawList.begin(); entity != drawList.end(); entity++)
550    if ((*entity)->isVisible())
551      (*entity)->draw();
552}
553
554
555void GameWorld::applyCameraSettings()
556{
557  this->dataTank->localCamera->apply ();
558  this->dataTank->localCamera->project ();
559  GraphicsEngine::storeMatrices();
560}
561
562
563
564/**
565 * reflection rendering for water surfaces
566 */
567void GameWorld::renderPassReflection()
568{
569  // clear buffer
570  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
571  //  glLoadIdentity();
572
573  MappedWater* mw;
574
575  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
576       it != MappedWater::objectList().end();
577       ++it)
578  {
579    mw =  (*it);
580
581    //camera and light
582    //this->dataTank->localCamera->apply ();
583    //this->dataTank->localCamera->project ();
584
585    LightManager::getInstance()->draw();
586
587
588    // prepare for reflection rendering
589    mw->activateReflection();
590
591    // draw everything to be included in the reflection
592    this->drawEntityList(State::getObjectManager()->getReflectionList());
593    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
594    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
595
596    // clean up from reflection rendering
597    mw->deactivateReflection();
598  }
599
600}
601
602
603/**
604 *  refraction rendering for water surfaces
605 */
606void GameWorld::renderPassRefraction()
607{
608  // clear buffer
609  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
610  //glLoadIdentity();
611
612  MappedWater* mw;
613
614  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
615       it != MappedWater::objectList().end();
616       ++it)
617  {
618    mw =  dynamic_cast<MappedWater*>(*it);
619
620    //camera and light
621    //this->dataTank->localCamera->apply ();
622    //this->dataTank->localCamera->project ();
623    // prepare for reflection rendering
624    mw->activateRefraction();
625
626
627    LightManager::getInstance()->draw();
628    // draw everything to be included in the reflection
629    this->drawEntityList(State::getObjectManager()->getReflectionList());
630    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
631    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
632
633    // clean up from reflection rendering
634    mw->deactivateRefraction();
635  }
636}
637
638
639/**
640 *  this render pass renders the whole wolrd
641 */
642void GameWorld::renderPassAll()
643{
644  // clear buffer
645  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
646  GraphicsEngine* engine = GraphicsEngine::getInstance();
647
648
649  // glEnable(GL_DEPTH_TEST);
650  // glEnable(GL_LIGHTING);
651
652  // set Lighting
653  LightManager::getInstance()->draw();
654
655  // only render the world if its not dedicated mode
656  if( !GraphicsEngine::getInstance()->isDedicated())
657  {
658    /* Draw the BackGround */
659    this->drawEntityList(State::getObjectManager()->getEntityList(OM_BACKGROUND));
660    engine->drawBackgroundElements();
661
662    /* draw all WorldEntiy groups */
663    for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
664      this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
665
666    AtmosphericEngine::getInstance()->draw();
667
668    if( unlikely( this->showBV))
669    {
670      CDEngine* engine = CDEngine::getInstance();
671      for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
672        engine->drawBV(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]), this->showBVLevel);
673    }
674
675    if( unlikely(this->showPNodes))
676      PNode::getNullParent()->debugDraw(0);
677
678    // draw the game ruls
679    if( likely(this->dataTank->gameRule != NULL))
680      this->dataTank->gameRule->draw();
681  }
682
683  engine->draw();
684}
685
686
687/**
688 *  shows the loading screen
689 */
690void GameWorld::displayLoadScreen ()
691{
692  PRINTF(3)("GameWorld::displayLoadScreen - start\n");
693  this->dataTank->glmis = new GLMenuImageScreen();
694  this->dataTank->glmis->setMaximum(8);
695  PRINTF(3)("GameWorld::displayLoadScreen - end\n");
696}
697
698
699/**
700 *  removes the loadscreen, and changes over to the game
701 */
702void GameWorld::releaseLoadScreen()
703{
704  PRINTF(3)("GameWorld::releaseLoadScreen - start\n");
705  this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum());
706  PRINTF(3)("GameWorld::releaseLoadScreen - end\n");
707}
708
709
710
711/**
712 * @brief toggles the PNode visibility in the world (drawn as boxes)
713 */
714void GameWorld::togglePNodeVisibility()
715{
716  this->showPNodes = !this->showPNodes;
717};
718
719
720/**
721 * @brief toggles the bounding volume (BV) visibility
722*/
723void GameWorld::toggleBVVisibility(int level)
724{
725  if( level < 1)
726    this->showBV = false;
727  else
728  {
729    this->showBV = true;
730    this->showBVLevel = level;
731  }
732
733};
734
Note: See TracBrowser for help on using the repository browser.