Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/ai/src/story_entities/game_world.cc @ 10040

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