/* orxonox - the future of 3D-vertical-scrollers Copyright (C) 2004 orx This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. ### File Specific: main-programmer: Patrick Boenzli co-programmer: Christian Meyer co-programmer: Benjamin Grauer */ #define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD #include "game_world.h" #include "game_world_data.h" #include "util/loading/resource_manager.h" #include "state.h" #include "util/loading/game_loader.h" #include "util/timer.h" #include "player.h" #include "camera.h" #include "environment.h" #include "terrain.h" #include "test_entity.h" #include "terrain.h" #include "playable.h" #include "environments/mapped_water.h" #include "light.h" #include "util/loading/factory.h" #include "util/loading/load_param_xml.h" #include "loading/fast_factory.h" #include "shell_command.h" #include "graphics_engine.h" #include "weather_effects/atmospheric_engine.h" #include "event_handler.h" #include "sound_engine.h" #include "cd_engine.h" #include "network_manager.h" #include "physics_engine.h" #include "glmenu_imagescreen.h" #include "shell.h" #include "ogg_player.h" #include "shader.h" #include "animation_player.h" #include "game_rules.h" #include "script_class.h" ObjectListDefinition(GameWorld); CREATE_SCRIPTABLE_CLASS(GameWorld, addMethod("setPlaymode", Executor1(&GameWorld::setPlaymode)) ->addMethod("setSoundtrack", Executor1(&GameWorld::setSoundtrack)) ); SHELL_COMMAND(speed, GameWorld, setSpeed) ->describe("set the Speed of the Level"); SHELL_COMMAND(playmode, GameWorld, setPlaymode) ->describe("Set the Playmode of the current Level") ->completionPlugin(0, OrxShell::CompletorStringArray(Playable::playmodeNames, Playable::PlaymodeCount)); SHELL_COMMAND(togglePNodeVisibility, GameWorld, togglePNodeVisibility); SHELL_COMMAND(showBVLevel, GameWorld, toggleBVVisibility); GameWorld::GameWorld() : StoryEntity() { this->registerObject(this, GameWorld::_objectList); this->setName("Preloaded World - no name yet"); this->gameTime = 0.0f; this->setSpeed(1.0f); this->shell = NULL; this->showPNodes = false; this->showBV = false; this->showBVLevel = 3; this->dataXML = NULL; this->gameRules = NULL; } /** * remove the GameWorld from memory * * delete everything explicitly, that isn't contained in the parenting tree! * things contained in the tree are deleted automaticaly */ GameWorld::~GameWorld () { PRINTF(4)("Deleted GameWorld\n"); } /** * loads the parameters of a GameWorld from an XML-element * @param root the XML-element to load from */ void GameWorld::loadParams(const TiXmlElement* root) { StoryEntity::loadParams(root); PRINTF(4)("Loaded GameWorld specific stuff\n"); } /** * this is executed just before load * * since the load function sometimes needs data, that has been initialized * before the load and after the proceeding storyentity has finished */ ErrorMessage GameWorld::init() { /* init the world interface */ this->shell = new OrxShell::Shell(); State::setCurrentStoryEntity(dynamic_cast(this)); this->dataTank->init(); /* initialize some engines and graphical elements */ AnimationPlayer::getInstance(); PhysicsEngine::getInstance(); CREngine::getInstance(); State::setScriptManager(&this->scriptManager); return ErrorMessage(); } /** * loads the GameWorld by initializing all resources, and set their default values. */ ErrorMessage GameWorld::loadData() { this->displayLoadScreen(); State::setScriptManager(&this->scriptManager); PRINTF(0)("Loading the GameWorld\n"); PRINTF(3)("> Loading world: '%s'\n", getLoadFile().c_str()); // TiXmlElement* element; // GameLoader* loader = GameLoader::getInstance(); if( getLoadFile().empty()) { PRINTF(1)("GameWorld has no path specified for loading\n"); return (ErrorMessage(213,"Path not specified","GameWorld::load()")); } TiXmlDocument* XMLDoc = new TiXmlDocument( getLoadFile()); // load the xml world file for further loading if( !XMLDoc->LoadFile()) { PRINTF(1)("loading XML File: %s @ %s:l%d:c%d\n", XMLDoc->ErrorDesc(), this->getLoadFile().c_str(), XMLDoc->ErrorRow(), XMLDoc->ErrorCol()); delete XMLDoc; return ErrorMessage(213,"XML File parsing error","GameWorld::load()"); } // check basic validity TiXmlElement* root = XMLDoc->RootElement(); assert( root != NULL); if( root == NULL || root->Value() == NULL || strcmp( root->Value(), "WorldDataFile")) { // report an error PRINTF(1)("Specified XML File is not an orxonox world data file (WorldDataFile element missing)\n"); delete XMLDoc; return ErrorMessage(213,"Path not a WorldDataFile","GameWorld::load()"); } /* the whole loading process for the GameWorld */ this->dataTank->loadData(root); this->dataXML = (TiXmlElement*)root->Clone(); //remove this after finished testing !!!! //Object* obj= new Object(); //obj->setName("Obj"); //Account* a = new Account(); //a->setName("a"); //Account *b = new Account(30); //b->setName("b"); LoadParamXML(root, "ScriptManager", &this->scriptManager, ScriptManager, loadParams); delete XMLDoc; this->releaseLoadScreen(); return ErrorMessage(); } /** * unload the data of this GameWorld */ ErrorMessage GameWorld::unloadData() { PRINTF(3)("GameWorld::~GameWorld() - unloading the current GameWorld\n"); this->scriptManager.flush(); delete this->shell; this->dataTank->unloadData(); this->shell = NULL; delete AnimationPlayer::getInstance(); delete PhysicsEngine::getInstance(); delete CREngine::getInstance(); State::setCurrentStoryEntity(NULL); if (this->dataXML) delete this->dataXML; return ErrorMessage(); } void GameWorld::setSoundtrack(const std::string& soundTrack) { if (this->dataTank != NULL) { this->dataTank->setSoundTrack(soundTrack); this->dataTank->music->play(); } } /** * starts the GameWorld */ bool GameWorld::start() { this->bPaused = false; this->bRunning = true; State::setScriptManager(&this->scriptManager); //make sure we have the right script manager this->run(); return true; } /** * stops the world. */ bool GameWorld::stop() { PRINTF(3)("GameWorld::stop() - got stop signal\n"); State::setScriptManager(NULL); return (this->bRunning = false); } /** * pauses the game */ bool GameWorld::pause() { return (this->bPaused = true); } /** * ends the pause Phase */ bool GameWorld::resume() { return(this->bPaused = false); } /** * main loop of the world: executing all world relevant function * * in this loop we synchronize (if networked), handle input events, give the heart-beat to * all other member-entities of the world (tick to player, enemies etc.), checking for * collisions drawing everything to the screen. */ void GameWorld::run() { PRINTF(3)("GameWorld::mainLoop() - Entering main loop\n"); // initialize Timing this->cycle = 0; for (unsigned int i = 0; i < TICK_SMOOTH_VALUE; i++) this->frameTimes[i] = 0.01f; this->dtS = 0.0f; this->lastFrame = Timer::getNow(); if (this->dataTank->music != NULL) this->dataTank->music->play(); while( this->bRunning) /* @todo implement pause */ { /* process intput */ this->handleInput (); if( !this->bRunning) break; /* network synchronisation */ this->synchronize (); /* process time */ this->tick (); /* update the state */ //this->update (); /// LESS REDUNDANCY. // PNode::getNullParent()->updateNode(this->dtS); PNode::getNullParent()->updateNode(this->dtS); /* collision detection */ this->collisionDetection (); /* collision reaction */ this->collisionReaction (); /* check the game rules */ this->checkGameRules(); /* update the state */ this->update (); /* draw everything */ this->display (); } PRINTF(0)("GameWorld::mainLoop() - Exiting the main loop\n"); } void GameWorld::setPlaymode(Playable::Playmode playmode) { if (this->dataTank->localPlayer && this->dataTank->localPlayer->getPlayable() && this->dataTank->localPlayer->getPlayable()->setPlaymode(playmode)) { PRINTF(4)("Set Playmode to %d:%s\n", playmode, Playable::playmodeToString(playmode).c_str()); } else { PRINTF(2)("Unable to set Playmode %d:'%s'\n", playmode, Playable::playmodeToString(playmode).c_str()); } } void GameWorld::setPlaymode(const std::string& playmode) { this->setPlaymode(Playable::stringToPlaymode(playmode)); } /** * synchronize local data with remote data */ void GameWorld::synchronize () {} /** * run all input processing the command node is the central input event dispatcher. the node uses the even-queue from sdl and has its own event-passing-queue. */ void GameWorld::handleInput () { EventHandler::getInstance()->process(); } /** * @brief ticks a WorldEntity list * @param entityList list of the WorldEntities * @param dt time passed since last frame */ void GameWorld::tick(ObjectManager::EntityList entityList, float dt) { ObjectManager::EntityList::iterator entity, next; next = entityList.begin(); while (next != entityList.end()) { entity = next++; (*entity)->tick(dt); } } /** * advance the timeline * * this calculates the time used to process one frame (with all input handling, drawing, etc) * the time is mesured in ms and passed to all world-entities and other classes that need * a heart-beat. */ void GameWorld::tick () { if( !this->bPaused) { // CALCULATE FRAMERATE Uint32 frameTimesIndex; Uint32 i; double currentFrame = Timer::getNow(); if (currentFrame - this->lastFrame < .01) { SDL_Delay((int)(1000.0 * (0.01 - (currentFrame - lastFrame)))); currentFrame = Timer::getNow(); } frameTimesIndex = this->cycle % TICK_SMOOTH_VALUE; this->frameTimes[frameTimesIndex] = currentFrame - this->lastFrame; this->lastFrame = currentFrame; ++this->cycle; this->dtS = 0.0; for (i = 0; i < TICK_SMOOTH_VALUE; i++) this->dtS += this->frameTimes[i]; this->dtS = this->dtS / TICK_SMOOTH_VALUE * speed; // TICK everything for (i = 0; i < this->dataTank->tickLists.size(); ++i) this->tick(this->dataTank->objectManager->getEntityList(this->dataTank->tickLists[i]), this->dtS); /* update tick the rest */ this->dataTank->localCamera->tick(this->dtS); AnimationPlayer::getInstance()->tick(this->dtS); PhysicsEngine::getInstance()->tick(this->dtS); GraphicsEngine::getInstance()->tick(this->dtS); AtmosphericEngine::getInstance()->tick(this->dtS); if( likely(this->dataTank->gameRule != NULL)) this->dataTank->gameRule->tick(this->dtS); } } /** * this function gives the world a consistant state * * after ticking (updating the world state) this will give a constistant * state to the whole system. */ void GameWorld::update() { PNode::getNullParent()->updateNode (this->dtS); OrxSound::SoundEngine::getInstance()->update(); this->applyCameraSettings(); GraphicsEngine::getInstance()->update(this->dtS); } /** * kicks the CDEngine to detect the collisions between the object groups in the world */ void GameWorld::collisionDetection() { // object-object collision detection CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00), this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ)); CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01), this->dataTank->objectManager->getEntityList(OM_GROUP_00_PROJ)); CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01), this->dataTank->objectManager->getEntityList(OM_GROUP_00)); CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01), this->dataTank->objectManager->getEntityList(OM_GROUP_02)); CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_02), this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ)); CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00), this->dataTank->objectManager->getEntityList(OM_COMMON)); CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01), this->dataTank->objectManager->getEntityList(OM_COMMON)); // ground collision detection: BSP Model CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_00)); CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_01)); } void GameWorld::collisionReaction() { CREngine::getInstance()->handleCollisions(); } /** * check the game rules: winning conditions, etc. * */ void GameWorld::checkGameRules() { if( this->gameRules) this->gameRules->tick(this->dtS); } /** * render the current frame * * clear all buffers and draw the world */ void GameWorld::display () { // if this server is a dedicated server the game workd does not need to be drawn if( !GraphicsEngine::getInstance()->isDedicated()) { // render the reflection texture this->renderPassReflection(); // redner the refraction texture this->renderPassRefraction(); } // render all this->renderPassAll(); // flip buffers GraphicsEngine::swapBuffers(); } /** * @brief draws all entities in the list drawList * @param drawList the List of entities to draw. */ void GameWorld::drawEntityList(const ObjectManager::EntityList& drawList) const { ObjectManager::EntityList::const_iterator entity; for (entity = drawList.begin(); entity != drawList.end(); entity++) if ((*entity)->isVisible()) (*entity)->draw(); } void GameWorld::applyCameraSettings() { this->dataTank->localCamera->apply (); this->dataTank->localCamera->project (); GraphicsEngine::storeMatrices(); } /** * reflection rendering for water surfaces */ void GameWorld::renderPassReflection() { // clear buffer glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // glLoadIdentity(); MappedWater* mw; for (ObjectList::const_iterator it = MappedWater::objectList().begin(); it != MappedWater::objectList().end(); ++it) { mw = (*it); //camera and light //this->dataTank->localCamera->apply (); //this->dataTank->localCamera->project (); LightManager::getInstance()->draw(); // prepare for reflection rendering mw->activateReflection(); // draw everything to be included in the reflection this->drawEntityList(State::getObjectManager()->getReflectionList()); // for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i) // this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i])); // clean up from reflection rendering mw->deactivateReflection(); } } /** * refraction rendering for water surfaces */ void GameWorld::renderPassRefraction() { // clear buffer glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //glLoadIdentity(); MappedWater* mw; for (ObjectList::const_iterator it = MappedWater::objectList().begin(); it != MappedWater::objectList().end(); ++it) { mw = dynamic_cast(*it); //camera and light //this->dataTank->localCamera->apply (); //this->dataTank->localCamera->project (); // prepare for reflection rendering mw->activateRefraction(); LightManager::getInstance()->draw(); // draw everything to be included in the reflection this->drawEntityList(State::getObjectManager()->getReflectionList()); // for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i) // this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i])); // clean up from reflection rendering mw->deactivateRefraction(); } } /** * this render pass renders the whole wolrd */ void GameWorld::renderPassAll() { // clear buffer glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); GraphicsEngine* engine = GraphicsEngine::getInstance(); // glEnable(GL_DEPTH_TEST); // glEnable(GL_LIGHTING); // set Lighting LightManager::getInstance()->draw(); // only render the world if its not dedicated mode if( !GraphicsEngine::getInstance()->isDedicated()) { /* Draw the BackGround */ this->drawEntityList(State::getObjectManager()->getEntityList(OM_BACKGROUND)); engine->drawBackgroundElements(); /* draw all WorldEntiy groups */ for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i) this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i])); AtmosphericEngine::getInstance()->draw(); if( unlikely( this->showBV)) { CDEngine* engine = CDEngine::getInstance(); for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i) engine->drawBV(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]), this->showBVLevel); } if( unlikely(this->showPNodes)) PNode::getNullParent()->debugDraw(0); // draw the game ruls if( likely(this->dataTank->gameRule != NULL)) this->dataTank->gameRule->draw(); } engine->draw(); } /** * shows the loading screen */ void GameWorld::displayLoadScreen () { PRINTF(3)("GameWorld::displayLoadScreen - start\n"); this->dataTank->glmis = new GLMenuImageScreen(); this->dataTank->glmis->setMaximum(8); PRINTF(3)("GameWorld::displayLoadScreen - end\n"); } /** * removes the loadscreen, and changes over to the game */ void GameWorld::releaseLoadScreen() { PRINTF(3)("GameWorld::releaseLoadScreen - start\n"); this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum()); PRINTF(3)("GameWorld::releaseLoadScreen - end\n"); } /** * @brief toggles the PNode visibility in the world (drawn as boxes) */ void GameWorld::togglePNodeVisibility() { this->showPNodes = !this->showPNodes; }; /** * @brief toggles the bounding volume (BV) visibility */ void GameWorld::toggleBVVisibility(int level) { if( level < 1) this->showBV = false; else { this->showBV = true; this->showBVLevel = level; } };