Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/story_entities/game_world.cc @ 9185

Last change on this file since 9185 was 9110, checked in by bensch, 18 years ago

orxonox/trunk: merged the Presentation back

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