Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/new_class_id/src/story_entities/game_world.cc @ 9723

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

orxonox/trunk: safer smart-pointer

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