Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 8233 was 8095, checked in by stefalie, 19 years ago

water: refreshed textures dont work if we use more than one texture unit in a material

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/dudvmap.bmp"));
135  }
136  imageSelector->showAll();
137  imageSelector->setAbsCoor2D(400, 30);
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      // prepare for reflection rendering
583      mw->activateReflection();
584
585      //camera and light
586      this->dataTank->localCamera->apply ();
587      this->dataTank->localCamera->project ();
588      LightManager::getInstance()->draw();
589      // draw everything to be included in the reflection
590      this->drawEntityList(State::getObjectManager()->getReflectionList());
591//       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
592//         this->drawEntityList(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]));
593
594      // clean up from reflection rendering
595      mw->deactivateReflection();
596    }
597  }
598
599}
600
601
602/**
603 *  refraction rendering for water surfaces
604 */
605void GameWorld::renderPassRefraction()
606{
607
608    // clear buffer
609  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
610  glLoadIdentity();
611
612  const std::list<BaseObject*>* reflectedWaters;
613  MappedWater* mw;
614
615  if( (reflectedWaters = ClassList::getList(CL_MAPPED_WATER)) != NULL)
616  {
617    std::list<BaseObject*>::const_iterator it;
618    for (it = reflectedWaters->begin(); it != reflectedWaters->end(); it++)
619    {
620      mw =  dynamic_cast<MappedWater*>(*it);
621
622      // prepare for reflection rendering
623      mw->activateRefraction();
624
625      //camera and light
626      this->dataTank->localCamera->apply ();
627      this->dataTank->localCamera->project ();
628      LightManager::getInstance()->draw();
629      // draw everything to be included in the reflection
630      this->drawEntityList(State::getObjectManager()->getReflectionList());
631//       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
632//         this->drawEntityList(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]));
633
634      // clean up from reflection rendering
635      mw->deactivateRefraction();
636    }
637  }
638}
639
640
641/**
642 *  this render pass renders the whole wolrd
643 */
644void GameWorld::renderPassAll()
645{
646  // clear buffer
647  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
648  GraphicsEngine* engine = GraphicsEngine::getInstance();
649
650
651  AtmosphericEngine::getInstance()->draw();
652
653  glEnable(GL_DEPTH_TEST);
654  glEnable(GL_LIGHTING);
655
656  // set camera
657  this->dataTank->localCamera->apply ();
658  this->dataTank->localCamera->project ();
659  LightManager::getInstance()->draw();
660
661  this->drawEntityList(State::getObjectManager()->getObjectList(OM_BACKGROUND));
662  engine->drawBackgroundElements();
663
664  /* draw all WorldEntiy groups */
665  for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
666    this->drawEntityList(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]));
667
668
669  if( unlikely( this->showBV))
670  {
671    CDEngine* engine = CDEngine::getInstance();
672    for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
673      engine->drawBV(State::getObjectManager()->getObjectList(this->dataTank->drawLists[i]), this->showBVLevel);
674  }
675
676  if( unlikely(this->showPNodes))
677    PNode::getNullParent()->debugDraw(0);
678
679  engine->draw();
680
681  // draw the game ruls
682  if( likely(this->dataTank->gameRule != NULL))
683    this->dataTank->gameRule->draw();
684}
685
686
687/**
688 *  shows the loading screen
689 */
690void GameWorld::displayLoadScreen ()
691{
692  PRINTF(3)("GameWorld::displayLoadScreen - start\n");
693  this->dataTank->glmis = new GLMenuImageScreen();
694  this->dataTank->glmis->setMaximum(8);
695  PRINTF(3)("GameWorld::displayLoadScreen - end\n");
696}
697
698
699/**
700 *  removes the loadscreen, and changes over to the game
701 */
702void GameWorld::releaseLoadScreen ()
703{
704  PRINTF(3)("GameWorld::releaseLoadScreen - start\n");
705  this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum());
706  PRINTF(3)("GameWorld::releaseLoadScreen - end\n");
707}
708
709
710
711/**
712 * @brief toggles the PNode visibility in the world (drawn as boxes)
713 */
714void GameWorld::togglePNodeVisibility()
715{
716  this->showPNodes = !this->showPNodes;
717};
718
719
720/**
721 * @brief toggles the bounding volume (BV) visibility
722*/
723void GameWorld::toggleBVVisibility(int level)
724{
725  if( level < 1)
726    this->showBV = false;
727  else
728  {
729    this->showBV = true;
730    this->showBVLevel = level;
731  }
732
733};
734
Note: See TracBrowser for help on using the repository browser.