Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/heathaze/src/story_entities/game_world.cc @ 10660

Last change on this file since 10660 was 10294, checked in by snellen, 18 years ago

prepared scripted levelswitch

File size: 18.6 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  while( this->bRunning) /* @todo implement pause */
309  {
310    /* process intput */
311    this->handleInput ();
312    if( !this->bRunning)
313      break;
314
315    /* network synchronisation */
316    this->synchronize ();
317    /* process time */
318    this->tick ();
319
320
321    /* update the state */
322    //this->update (); /// LESS REDUNDANCY.
323    //      PNode::getNullParent()->updateNode(this->dtS);
324    PNode::getNullParent()->updateNode(this->dtS);
325
326    /* collision detection */
327    this->collisionDetection ();
328    /* collision reaction */
329    this->collisionReaction ();
330
331    /* check the game rules */
332    this->checkGameRules();
333
334    /* update the state */
335    this->update ();
336    /* draw everything */
337    this->display ();
338
339  }
340
341  PRINTF(4)("GameWorld::mainLoop() - Exiting the main loop\n");
342}
343
344
345void GameWorld::setPlaymode(Playable::Playmode playmode)
346{
347  if (this->dataTank->localPlayer &&
348      this->dataTank->localPlayer->getPlayable() &&
349      this->dataTank->localPlayer->getPlayable()->setPlaymode(playmode))
350  {
351    PRINTF(4)("Set Playmode to %d:%s\n", playmode, Playable::playmodeToString(playmode).c_str());
352  }
353  else
354  {
355    PRINTF(2)("Unable to set Playmode %d:'%s'\n", playmode, Playable::playmodeToString(playmode).c_str());
356  }
357}
358
359void GameWorld::setPlaymode(const std::string& playmode)
360{
361  this->setPlaymode(Playable::stringToPlaymode(playmode));
362}
363
364/**
365 *  synchronize local data with remote data
366*/
367void GameWorld::synchronize ()
368{}
369
370
371/**
372 *  run all input processing
373
374   the command node is the central input event dispatcher. the node uses the even-queue from
375   sdl and has its own event-passing-queue.
376*/
377void GameWorld::handleInput ()
378{
379  EventHandler::getInstance()->process();
380}
381
382
383/**
384 * @brief ticks a WorldEntity list
385 * @param entityList list of the WorldEntities
386 * @param dt time passed since last frame
387 */
388void GameWorld::tick(ObjectManager::EntityList entityList, float dt)
389{
390  ObjectManager::EntityList::iterator entity, next;
391  next = entityList.begin();
392  while (next != entityList.end())
393  {
394    entity = next++;
395    (*entity)->tick(dt);
396  }
397}
398
399
400/**
401 *  advance the timeline
402 *
403 * this calculates the time used to process one frame (with all input handling, drawing, etc)
404 * the time is mesured in ms and passed to all world-entities and other classes that need
405 * a heart-beat.
406 */
407void GameWorld::tick ()
408{
409  if( !this->bPaused)
410  {
411    // CALCULATE FRAMERATE
412    Uint32 frameTimesIndex;
413    Uint32 i;
414    double currentFrame = Timer::getNow();
415
416    if (currentFrame - this->lastFrame < .01)
417    {
418      SDL_Delay((int)(1000.0 * (0.01 - (currentFrame - lastFrame))));
419      currentFrame = Timer::getNow();
420    }
421
422
423    frameTimesIndex = this->cycle % TICK_SMOOTH_VALUE;
424    this->frameTimes[frameTimesIndex] = currentFrame - this->lastFrame;
425    this->lastFrame = currentFrame;
426    ++this->cycle;
427    this->dtS = 0.0;
428    for (i = 0; i < TICK_SMOOTH_VALUE; i++)
429      this->dtS += this->frameTimes[i];
430    this->dtS = this->dtS / TICK_SMOOTH_VALUE * speed;
431
432    // TICK everything
433    for (i = 0; i < this->dataTank->tickLists.size(); ++i)
434      this->tick(this->dataTank->objectManager->getEntityList(this->dataTank->tickLists[i]), this->dtS);
435
436    /* update tick the rest */
437    this->dataTank->localCamera->tick(this->dtS);
438    AnimationPlayer::getInstance()->tick(this->dtS);
439    PhysicsEngine::getInstance()->tick(this->dtS);
440
441    GraphicsEngine::getInstance()->tick(this->dtS);
442    AtmosphericEngine::getInstance()->tick(this->dtS);
443
444    if( likely(this->dataTank->gameRule != NULL))
445      this->dataTank->gameRule->tick(this->dtS);
446
447  }
448}
449
450
451/**
452 *  this function gives the world a consistant state
453 *
454 * after ticking (updating the world state) this will give a constistant
455 * state to the whole system.
456 */
457void GameWorld::update()
458{
459  PNode::getNullParent()->updateNode (this->dtS);
460  OrxSound::SoundEngine::getInstance()->update();
461
462  this->applyCameraSettings();
463  GraphicsEngine::getInstance()->update(this->dtS);
464}
465
466
467/**
468 * kicks the CDEngine to detect the collisions between the object groups in the world
469 */
470void GameWorld::collisionDetection()
471{
472  // object-object collision detection
473  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
474      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
475  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
476      this->dataTank->objectManager->getEntityList(OM_GROUP_00_PROJ));
477  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
478      this->dataTank->objectManager->getEntityList(OM_GROUP_00));
479
480  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
481      this->dataTank->objectManager->getEntityList(OM_GROUP_02));
482  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_02),
483      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
484
485
486  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
487      this->dataTank->objectManager->getEntityList(OM_COMMON));
488  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
489      this->dataTank->objectManager->getEntityList(OM_COMMON));
490
491  // ground collision detection: BSP Model
492  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_00));
493  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_01));
494}
495
496
497void GameWorld::collisionReaction()
498{
499  CREngine::getInstance()->handleCollisions();
500}
501
502
503/**
504 *  check the game rules: winning conditions, etc.
505 *
506 */
507void GameWorld::checkGameRules()
508{
509  if( this->gameRules)
510    this->gameRules->tick(this->dtS);
511}
512
513
514/**
515 *  render the current frame
516 *
517 * clear all buffers and draw the world
518 */
519void GameWorld::display ()
520{
521
522  // if this server is a dedicated server the game workd does not need to be drawn
523  if( !GraphicsEngine::getInstance()->isDedicated())
524  {
525    // render the reflection texture
526    this->renderPassReflection();
527    // redner the refraction texture
528    this->renderPassRefraction();
529  }
530  // render all
531  this->renderPassAll();
532
533  // flip buffers
534  GraphicsEngine::swapBuffers();
535}
536
537
538/**
539 * @brief draws all entities in the list drawList
540 * @param drawList the List of entities to draw.
541 */
542void GameWorld::drawEntityList(const ObjectManager::EntityList& drawList) const
543{
544  ObjectManager::EntityList::const_iterator entity;
545  for (entity = drawList.begin(); entity != drawList.end(); entity++)
546    if ((*entity)->isVisible())
547      (*entity)->draw();
548}
549
550
551void GameWorld::applyCameraSettings()
552{
553  this->dataTank->localCamera->apply ();
554  this->dataTank->localCamera->project ();
555  GraphicsEngine::storeMatrices();
556}
557
558
559
560/**
561 * reflection rendering for water surfaces
562 */
563void GameWorld::renderPassReflection()
564{
565  // clear buffer
566  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
567  //  glLoadIdentity();
568
569  MappedWater* mw;
570
571  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
572       it != MappedWater::objectList().end();
573       ++it)
574  {
575    mw =  (*it);
576
577    //camera and light
578    //this->dataTank->localCamera->apply ();
579    //this->dataTank->localCamera->project ();
580
581    LightManager::getInstance()->draw();
582
583
584    // prepare for reflection rendering
585    mw->activateReflection();
586
587    // draw everything to be included in the reflection
588    this->drawEntityList(State::getObjectManager()->getReflectionList());
589    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
590    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
591
592    // clean up from reflection rendering
593    mw->deactivateReflection();
594  }
595
596}
597
598
599/**
600 *  refraction rendering for water surfaces
601 */
602void GameWorld::renderPassRefraction()
603{
604  // clear buffer
605  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
606  //glLoadIdentity();
607
608  MappedWater* mw;
609
610  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
611       it != MappedWater::objectList().end();
612       ++it)
613  {
614    mw =  dynamic_cast<MappedWater*>(*it);
615
616    //camera and light
617    //this->dataTank->localCamera->apply ();
618    //this->dataTank->localCamera->project ();
619    // prepare for reflection rendering
620    mw->activateRefraction();
621
622
623    LightManager::getInstance()->draw();
624    // draw everything to be included in the reflection
625    this->drawEntityList(State::getObjectManager()->getReflectionList());
626    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
627    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
628
629    // clean up from reflection rendering
630    mw->deactivateRefraction();
631  }
632}
633
634
635/**
636 *  this render pass renders the whole wolrd
637 */
638void GameWorld::renderPassAll()
639{
640  // clear buffer
641  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
642  GraphicsEngine* engine = GraphicsEngine::getInstance();
643
644
645  // glEnable(GL_DEPTH_TEST);
646  // glEnable(GL_LIGHTING);
647
648  // set Lighting
649  LightManager::getInstance()->draw();
650
651  // only render the world if its not dedicated mode
652  if( !GraphicsEngine::getInstance()->isDedicated())
653  {
654    /* Draw the BackGround */
655    this->drawEntityList(State::getObjectManager()->getEntityList(OM_BACKGROUND));
656    engine->drawBackgroundElements();
657
658    /* draw all WorldEntiy groups */
659    for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
660      this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
661
662    AtmosphericEngine::getInstance()->draw();
663
664    if( unlikely( this->showBV))
665    {
666      CDEngine* engine = CDEngine::getInstance();
667      for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
668        engine->drawBV(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]), this->showBVLevel);
669    }
670
671    if( unlikely(this->showPNodes))
672      PNode::getNullParent()->debugDraw(0);
673
674    // draw the game ruls
675    if( likely(this->dataTank->gameRule != NULL))
676      this->dataTank->gameRule->draw();
677  }
678
679  engine->draw();
680}
681
682
683/**
684 *  shows the loading screen
685 */
686void GameWorld::displayLoadScreen ()
687{
688  PRINTF(3)("GameWorld::displayLoadScreen - start\n");
689  this->dataTank->glmis = new GLMenuImageScreen();
690  this->dataTank->glmis->setMaximum(8);
691  PRINTF(3)("GameWorld::displayLoadScreen - end\n");
692}
693
694
695/**
696 *  removes the loadscreen, and changes over to the game
697 */
698void GameWorld::releaseLoadScreen()
699{
700  PRINTF(3)("GameWorld::releaseLoadScreen - start\n");
701  this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum());
702  PRINTF(3)("GameWorld::releaseLoadScreen - end\n");
703}
704
705
706
707/**
708 * @brief toggles the PNode visibility in the world (drawn as boxes)
709 */
710void GameWorld::togglePNodeVisibility()
711{
712  this->showPNodes = !this->showPNodes;
713};
714
715
716/**
717 * @brief toggles the bounding volume (BV) visibility
718*/
719void GameWorld::toggleBVVisibility(int level)
720{
721  if( level < 1)
722    this->showBV = false;
723  else
724  {
725    this->showBV = true;
726    this->showBVLevel = level;
727  }
728
729};
730
Note: See TracBrowser for help on using the repository browser.