Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain/src/story_entities/game_world.cc @ 9242

Last change on this file since 9242 was 9140, checked in by bensch, 18 years ago

merged back

File size: 17.4 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 "util/loading/resource_manager.h"
23#include "state.h"
24#include "class_list.h"
25
26#include "util/loading/game_loader.h"
27#include "util/timer.h"
28
29#include "player.h"
30#include "camera.h"
31#include "environment.h"
32#include "test_entity.h"
33#include "terrain_entity.h"
34#include "playable.h"
35#include "environments/mapped_water.h"
36
37#include "light.h"
38
39#include "util/loading/factory.h"
40#include "util/loading/load_param.h"
41#include "fast_factory.h"
42#include "shell_command.h"
43
44#include "graphics_engine.h"
45#include "effects/atmospheric_engine.h"
46#include "event_handler.h"
47#include "sound_engine.h"
48#include "cd_engine.h"
49#include "network_manager.h"
50#include "physics_engine.h"
51#include "fields.h"
52
53#include "glmenu_imagescreen.h"
54#include "shell.h"
55
56#include "ogg_player.h"
57#include "shader.h"
58
59#include "animation_player.h"
60
61#include "game_rules.h"
62
63using namespace std;
64
65#include "script_class.h"
66CREATE_SCRIPTABLE_CLASS(GameWorld, CL_GAME_WORLD,
67                        addMethod("setPlaymode", ExecutorLua1<GameWorld,const std::string&>(&GameWorld::setPlaymode))
68                       );
69
70SHELL_COMMAND(speed, GameWorld, setSpeed) ->describe("set the Speed of the Level");
71SHELL_COMMAND(playmode, GameWorld, setPlaymode)
72->describe("Set the Playmode of the current Level")
73->completionPlugin(0, OrxShell::CompletorStringArray(Playable::playmodeNames, Playable::PlaymodeCount));
74
75SHELL_COMMAND(togglePNodeVisibility, GameWorld, togglePNodeVisibility);
76SHELL_COMMAND(showBVLevel, GameWorld, toggleBVVisibility);
77
78
79
80GameWorld::GameWorld()
81    : StoryEntity()
82{
83  this->setClassID(CL_GAME_WORLD, "GameWorld");
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(0)("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
234/**
235 *  starts the GameWorld
236 */
237bool GameWorld::start()
238{
239  this->bPaused = false;
240  this->bRunning = true;
241  State::setScriptManager(&this->scriptManager); //make sure we have the right script manager
242  this->run();
243
244  return true;
245}
246
247
248/**
249 *  stops the world.
250 */
251bool GameWorld::stop()
252{
253  PRINTF(3)("GameWorld::stop() - got stop signal\n");
254  State::setScriptManager(NULL);
255  return (this->bRunning = false);
256}
257
258
259/**
260 *  pauses the game
261 */
262bool GameWorld::pause()
263{
264  return (this->bPaused = true);
265}
266
267
268/**
269 *  ends the pause Phase
270 */
271bool GameWorld::resume()
272{
273  return(this->bPaused = false);
274}
275
276
277/**
278 *  main loop of the world: executing all world relevant function
279 *
280 * in this loop we synchronize (if networked), handle input events, give the heart-beat to
281 * all other member-entities of the world (tick to player, enemies etc.), checking for
282 * collisions drawing everything to the screen.
283 */
284void GameWorld::run()
285{
286  PRINTF(3)("GameWorld::mainLoop() - Entering main loop\n");
287
288  // initialize Timing
289  this->cycle = 0;
290  for (unsigned int i = 0; i < TICK_SMOOTH_VALUE; i++)
291    this->frameTimes[i] = 0.01f;
292  this->dtS = 0.0f;
293  this->lastFrame = Timer::getNow();
294
295  if (this->dataTank->music != NULL)
296    this->dataTank->music->play();
297
298  while( this->bRunning) /* @todo implement pause */
299  {
300    /* process intput */
301    this->handleInput ();
302    if( !this->bRunning)
303      break;
304
305    /* network synchronisation */
306    this->synchronize ();
307    /* process time */
308    this->tick ();
309
310
311    /* update the state */
312    //this->update (); /// LESS REDUNDANCY.
313//      PNode::getNullParent()->updateNode(this->dtS);
314    PNode::getNullParent()->updateNode(this->dtS);
315
316    /* collision detection */
317    this->collisionDetection ();
318    /* collision reaction */
319    this->collisionReaction ();
320
321    /* check the game rules */
322    this->checkGameRules();
323
324    /* update the state */
325    this->update ();
326    /* draw everything */
327    this->display ();
328
329  }
330
331  PRINTF(0)("GameWorld::mainLoop() - Exiting the main loop\n");
332}
333
334
335void GameWorld::setPlaymode(Playable::Playmode playmode)
336{
337  if (this->dataTank->localPlayer &&
338      this->dataTank->localPlayer->getPlayable() &&
339      this->dataTank->localPlayer->getPlayable()->setPlaymode(playmode))
340  {
341    PRINTF(4)("Set Playmode to %d:%s\n", playmode, Playable::playmodeToString(playmode).c_str());
342  }
343  else
344  {
345    PRINTF(2)("Unable to set Playmode %d:'%s'\n", playmode, Playable::playmodeToString(playmode).c_str());
346  }
347}
348
349void GameWorld::setPlaymode(const std::string& playmode)
350{
351  this->setPlaymode(Playable::stringToPlaymode(playmode));
352}
353
354/**
355 *  synchronize local data with remote data
356*/
357void GameWorld::synchronize ()
358{}
359
360
361/**
362 *  run all input processing
363
364   the command node is the central input event dispatcher. the node uses the even-queue from
365   sdl and has its own event-passing-queue.
366*/
367void GameWorld::handleInput ()
368{
369  EventHandler::getInstance()->process();
370}
371
372
373/**
374 * @brief ticks a WorldEntity list
375 * @param entityList list of the WorldEntities
376 * @param dt time passed since last frame
377 */
378void GameWorld::tick(ObjectManager::EntityList entityList, float dt)
379{
380  ObjectManager::EntityList::iterator entity, next;
381  next = entityList.begin();
382  while (next != entityList.end())
383  {
384    entity = next++;
385    (*entity)->tick(dt);
386  }
387}
388
389
390/**
391 *  advance the timeline
392 *
393 * this calculates the time used to process one frame (with all input handling, drawing, etc)
394 * the time is mesured in ms and passed to all world-entities and other classes that need
395 * a heart-beat.
396 */
397void GameWorld::tick ()
398{
399  if( !this->bPaused)
400  {
401    // CALCULATE FRAMERATE
402    Uint32 frameTimesIndex;
403    Uint32 i;
404    double currentFrame = Timer::getNow();
405
406    frameTimesIndex = this->cycle % TICK_SMOOTH_VALUE;
407    this->frameTimes[frameTimesIndex] = currentFrame - this->lastFrame;
408    this->lastFrame = currentFrame;
409    ++this->cycle;
410    this->dtS = 0.0;
411    for (i = 0; i < TICK_SMOOTH_VALUE; i++)
412      this->dtS += this->frameTimes[i];
413    this->dtS = this->dtS / TICK_SMOOTH_VALUE * speed;
414
415    // TICK everything
416    for (i = 0; i < this->dataTank->tickLists.size(); ++i)
417      this->tick(this->dataTank->objectManager->getObjectList(this->dataTank->tickLists[i]), this->dtS);
418
419    /* update tick the rest */
420    this->dataTank->localCamera->tick(this->dtS);
421    AnimationPlayer::getInstance()->tick(this->dtS);
422    PhysicsEngine::getInstance()->tick(this->dtS);
423
424    GraphicsEngine::getInstance()->tick(this->dtS);
425    AtmosphericEngine::getInstance()->tick(this->dtS);
426
427    if( likely(this->dataTank->gameRule != NULL))
428      this->dataTank->gameRule->tick(this->dtS);
429
430  }
431}
432
433
434/**
435 *  this function gives the world a consistant state
436 *
437 * after ticking (updating the world state) this will give a constistant
438 * state to the whole system.
439 */
440void GameWorld::update()
441{
442  PNode::getNullParent()->updateNode (this->dtS);
443  OrxSound::SoundEngine::getInstance()->update();
444
445  this->applyCameraSettings();
446  GraphicsEngine::getInstance()->update(this->dtS);
447}
448
449
450/**
451 * kicks the CDEngine to detect the collisions between the object groups in the world
452 */
453void GameWorld::collisionDetection()
454{
455  // object-object collision detection
456  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getObjectList(OM_GROUP_00),
457      this->dataTank->objectManager->getObjectList(OM_GROUP_01_PROJ));
458  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getObjectList(OM_GROUP_01),
459      this->dataTank->objectManager->getObjectList(OM_GROUP_00_PROJ));
460  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getObjectList(OM_GROUP_00),
461      this->dataTank->objectManager->getObjectList(OM_GROUP_01));
462
463  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getObjectList(OM_GROUP_00),
464      this->dataTank->objectManager->getObjectList(OM_COMMON));
465  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getObjectList(OM_GROUP_01),
466      this->dataTank->objectManager->getObjectList(OM_COMMON));
467
468  // ground collision detection: BSP Model
469  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getObjectList(OM_GROUP_00));
470  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getObjectList(OM_GROUP_01));
471}
472
473
474void GameWorld::collisionReaction()
475{
476  CREngine::getInstance()->handleCollisions();
477}
478
479
480/**
481 *  check the game rules: winning conditions, etc.
482 *
483 */
484void GameWorld::checkGameRules()
485{
486  if( this->gameRules)
487    this->gameRules->tick(this->dtS);
488}
489
490
491/**
492 *  render the current frame
493 *
494 * clear all buffers and draw the world
495 */
496void GameWorld::display ()
497{
498  // render the reflection texture
499  this->renderPassReflection();
500  // redner the refraction texture
501  this->renderPassRefraction();
502  // render all
503  this->renderPassAll();
504
505  // flip buffers
506  GraphicsEngine::swapBuffers();
507}
508
509
510/**
511 * @brief draws all entities in the list drawList
512 * @param drawList the List of entities to draw.
513 */
514void GameWorld::drawEntityList(const ObjectManager::EntityList& drawList) const
515{
516  ObjectManager::EntityList::const_iterator entity;
517  for (entity = drawList.begin(); entity != drawList.end(); entity++)
518    if ((*entity)->isVisible())
519      (*entity)->draw();
520}
521
522
523void GameWorld::applyCameraSettings()
524{
525  this->dataTank->localCamera->apply ();
526  this->dataTank->localCamera->project ();
527  GraphicsEngine::storeMatrices();
528}
529
530
531
532/**
533 * reflection rendering for water surfaces
534 */
535void GameWorld::renderPassReflection()
536{
537    // clear buffer
538  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
539//  glLoadIdentity();
540
541  const std::list<BaseObject*>* reflectedWaters;
542  MappedWater* mw;
543
544  if( (reflectedWaters = ClassList::getList(CL_MAPPED_WATER)) != NULL)
545  {
546    std::list<BaseObject*>::const_iterator it;
547    for (it = reflectedWaters->begin(); it != reflectedWaters->end(); it++)
548    {
549      mw =  dynamic_cast<MappedWater*>(*it);
550
551      //camera and light
552      //this->dataTank->localCamera->apply ();
553      //this->dataTank->localCamera->project ();
554
555      LightManager::getInstance()->draw();
556
557
558      // prepare for reflection rendering
559      mw->activateReflection();
560
561      // draw everything to be included in the reflection
562      this->drawEntityList(State::getObjectManager()->getReflectionList());
563//       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
564//         this->drawEntityList(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]));
565
566      // clean up from reflection rendering
567      mw->deactivateReflection();
568    }
569  }
570
571}
572
573
574/**
575 *  refraction rendering for water surfaces
576 */
577void GameWorld::renderPassRefraction()
578{
579    // clear buffer
580  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
581  //glLoadIdentity();
582
583  const std::list<BaseObject*>* reflectedWaters;
584  MappedWater* mw;
585
586  if( (reflectedWaters = ClassList::getList(CL_MAPPED_WATER)) != NULL)
587  {
588    std::list<BaseObject*>::const_iterator it;
589    for (it = reflectedWaters->begin(); it != reflectedWaters->end(); it++)
590    {
591      mw =  dynamic_cast<MappedWater*>(*it);
592
593      //camera and light
594      //this->dataTank->localCamera->apply ();
595      //this->dataTank->localCamera->project ();
596      // prepare for reflection rendering
597      mw->activateRefraction();
598
599
600      LightManager::getInstance()->draw();
601      // draw everything to be included in the reflection
602      this->drawEntityList(State::getObjectManager()->getReflectionList());
603//       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
604//         this->drawEntityList(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]));
605
606      // clean up from reflection rendering
607      mw->deactivateRefraction();
608    }
609  }
610}
611
612
613/**
614 *  this render pass renders the whole wolrd
615 */
616void GameWorld::renderPassAll()
617{
618  // clear buffer
619  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
620  GraphicsEngine* engine = GraphicsEngine::getInstance();
621
622
623  // glEnable(GL_DEPTH_TEST);
624  // glEnable(GL_LIGHTING);
625
626  // set Lighting
627  LightManager::getInstance()->draw();
628
629  /* Draw the BackGround */
630  this->drawEntityList(State::getObjectManager()->getObjectList(OM_BACKGROUND));
631  engine->drawBackgroundElements();
632
633  /* draw all WorldEntiy groups */
634  for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
635    this->drawEntityList(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]));
636
637  AtmosphericEngine::getInstance()->draw();
638
639  if( unlikely( this->showBV))
640  {
641    CDEngine* engine = CDEngine::getInstance();
642    for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
643      engine->drawBV(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]), this->showBVLevel);
644  }
645
646  if( unlikely(this->showPNodes))
647    PNode::getNullParent()->debugDraw(0);
648
649  engine->draw();
650
651  // draw the game ruls
652  if( likely(this->dataTank->gameRule != NULL))
653    this->dataTank->gameRule->draw();
654}
655
656
657/**
658 *  shows the loading screen
659 */
660void GameWorld::displayLoadScreen ()
661{
662  PRINTF(3)("GameWorld::displayLoadScreen - start\n");
663  this->dataTank->glmis = new GLMenuImageScreen();
664  this->dataTank->glmis->setMaximum(8);
665  PRINTF(3)("GameWorld::displayLoadScreen - end\n");
666}
667
668
669/**
670 *  removes the loadscreen, and changes over to the game
671 */
672void GameWorld::releaseLoadScreen ()
673{
674  PRINTF(3)("GameWorld::releaseLoadScreen - start\n");
675  this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum());
676  PRINTF(3)("GameWorld::releaseLoadScreen - end\n");
677}
678
679
680
681/**
682 * @brief toggles the PNode visibility in the world (drawn as boxes)
683 */
684void GameWorld::togglePNodeVisibility()
685{
686  this->showPNodes = !this->showPNodes;
687};
688
689
690/**
691 * @brief toggles the bounding volume (BV) visibility
692*/
693void GameWorld::toggleBVVisibility(int level)
694{
695  if( level < 1)
696    this->showBV = false;
697  else
698  {
699    this->showBV = true;
700    this->showBVLevel = level;
701  }
702
703};
704
Note: See TracBrowser for help on using the repository browser.