Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/water/src/story_entities/game_world.cc @ 8260

Last change on this file since 8260 was 8260, checked in by stefalie, 18 years ago

water: …

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