3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "environment.h"
24 Environment::Environment()
26 m_daynight_ratio = 0.5;
29 Environment::~Environment()
32 for(core::list<Player*>::Iterator i = m_players.begin();
33 i != m_players.end(); i++)
39 void Environment::addPlayer(Player *player)
41 DSTACK(__FUNCTION_NAME);
43 Check that peer_ids are unique.
44 Also check that names are unique.
45 Exception: there can be multiple players with peer_id=0
47 // If peer id is non-zero, it has to be unique.
48 if(player->peer_id != 0)
49 assert(getPlayer(player->peer_id) == NULL);
50 // Name has to be unique.
51 assert(getPlayer(player->getName()) == NULL);
53 m_players.push_back(player);
56 void Environment::removePlayer(u16 peer_id)
58 DSTACK(__FUNCTION_NAME);
60 for(core::list<Player*>::Iterator i = m_players.begin();
61 i != m_players.end(); i++)
64 if(player->peer_id != peer_id)
69 // See if there is an another one
70 // (shouldn't be, but just to be sure)
75 Player * Environment::getPlayer(u16 peer_id)
77 for(core::list<Player*>::Iterator i = m_players.begin();
78 i != m_players.end(); i++)
81 if(player->peer_id == peer_id)
87 Player * Environment::getPlayer(const char *name)
89 for(core::list<Player*>::Iterator i = m_players.begin();
90 i != m_players.end(); i++)
93 if(strcmp(player->getName(), name) == 0)
99 core::list<Player*> Environment::getPlayers()
104 core::list<Player*> Environment::getPlayers(bool ignore_disconnected)
106 core::list<Player*> newlist;
107 for(core::list<Player*>::Iterator
108 i = m_players.begin();
109 i != m_players.end(); i++)
113 if(ignore_disconnected)
115 // Ignore disconnected players
116 if(player->peer_id == 0)
120 newlist.push_back(player);
125 void Environment::printPlayers(std::ostream &o)
127 o<<"Players in environment:"<<std::endl;
128 for(core::list<Player*>::Iterator i = m_players.begin();
129 i != m_players.end(); i++)
132 o<<"Player peer_id="<<player->peer_id<<std::endl;
136 void Environment::setDayNightRatio(u32 r)
138 m_daynight_ratio = r;
141 u32 Environment::getDayNightRatio()
143 return m_daynight_ratio;
150 ServerEnvironment::ServerEnvironment(ServerMap *map):
152 m_random_spawn_timer(0)
156 ServerEnvironment::~ServerEnvironment()
162 void ServerEnvironment::serializePlayers(const std::string &savedir)
164 std::string players_path = savedir + "/players";
165 fs::CreateDir(players_path);
167 core::map<Player*, bool> saved_players;
169 std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
170 for(u32 i=0; i<player_files.size(); i++)
172 if(player_files[i].dir)
175 // Full path to this file
176 std::string path = players_path + "/" + player_files[i].name;
178 //dstream<<"Checking player file "<<path<<std::endl;
180 // Load player to see what is its name
181 ServerRemotePlayer testplayer;
183 // Open file and deserialize
184 std::ifstream is(path.c_str(), std::ios_base::binary);
185 if(is.good() == false)
187 dstream<<"Failed to read "<<path<<std::endl;
190 testplayer.deSerialize(is);
193 //dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
195 // Search for the player
196 std::string playername = testplayer.getName();
197 Player *player = getPlayer(playername.c_str());
200 dstream<<"Didn't find matching player, ignoring file "<<path<<std::endl;
204 //dstream<<"Found matching player, overwriting."<<std::endl;
206 // OK, found. Save player there.
208 // Open file and serialize
209 std::ofstream os(path.c_str(), std::ios_base::binary);
210 if(os.good() == false)
212 dstream<<"Failed to overwrite "<<path<<std::endl;
215 player->serialize(os);
216 saved_players.insert(player, true);
220 for(core::list<Player*>::Iterator i = m_players.begin();
221 i != m_players.end(); i++)
224 if(saved_players.find(player) != NULL)
226 /*dstream<<"Player "<<player->getName()
227 <<" was already saved."<<std::endl;*/
230 std::string playername = player->getName();
231 // Don't save unnamed player
234 //dstream<<"Not saving unnamed player."<<std::endl;
240 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false)
241 playername = "player";
242 std::string path = players_path + "/" + playername;
244 for(u32 i=0; i<1000; i++)
246 if(fs::PathExists(path) == false)
251 path = players_path + "/" + playername + itos(i);
255 dstream<<"WARNING: Didn't find free file for player"<<std::endl;
260 /*dstream<<"Saving player "<<player->getName()<<" to "
262 // Open file and serialize
263 std::ofstream os(path.c_str(), std::ios_base::binary);
264 if(os.good() == false)
266 dstream<<"WARNING: Failed to overwrite "<<path<<std::endl;
269 player->serialize(os);
270 saved_players.insert(player, true);
274 //dstream<<"Saved "<<saved_players.size()<<" players."<<std::endl;
277 void ServerEnvironment::deSerializePlayers(const std::string &savedir)
279 std::string players_path = savedir + "/players";
281 core::map<Player*, bool> saved_players;
283 std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
284 for(u32 i=0; i<player_files.size(); i++)
286 if(player_files[i].dir)
289 // Full path to this file
290 std::string path = players_path + "/" + player_files[i].name;
292 dstream<<"Checking player file "<<path<<std::endl;
294 // Load player to see what is its name
295 ServerRemotePlayer testplayer;
297 // Open file and deserialize
298 std::ifstream is(path.c_str(), std::ios_base::binary);
299 if(is.good() == false)
301 dstream<<"Failed to read "<<path<<std::endl;
304 testplayer.deSerialize(is);
307 dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
309 // Search for the player
310 std::string playername = testplayer.getName();
311 Player *player = getPlayer(playername.c_str());
312 bool newplayer = false;
315 dstream<<"Is a new player"<<std::endl;
316 player = new ServerRemotePlayer();
322 dstream<<"Reading player "<<testplayer.getName()<<" from "
324 // Open file and deserialize
325 std::ifstream is(path.c_str(), std::ios_base::binary);
326 if(is.good() == false)
328 dstream<<"Failed to read "<<path<<std::endl;
331 player->deSerialize(is);
339 void ServerEnvironment::step(float dtime)
341 DSTACK(__FUNCTION_NAME);
344 //bool free_move = g_settings.getBool("free_move");
345 bool footprints = g_settings.getBool("footprints");
348 //TimeTaker timer("Server m_map->timerUpdate()", g_device);
349 m_map->timerUpdate(dtime);
355 for(core::list<Player*>::Iterator i = m_players.begin();
356 i != m_players.end(); i++)
359 v3f playerpos = player->getPosition();
362 player->move(dtime, *m_map, 100*BS);
365 Add footsteps to grass
369 // Get node that is at BS/4 under player
370 v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS);
372 MapNode n = m_map->getNode(bottompos);
373 if(n.d == CONTENT_GRASS)
375 n.d = CONTENT_GRASS_FOOTSTEPS;
376 m_map->setNode(bottompos, n);
379 catch(InvalidPositionException &e)
388 for(core::map<u16, ServerActiveObject*>::Iterator
389 i = m_active_objects.getIterator();
390 i.atEnd()==false; i++)
392 ServerActiveObject* obj = i.getNode()->getValue();
393 // Step object, putting messages directly to the queue
394 obj->step(dtime, m_active_object_messages);
398 Remove (m_removed && m_known_by_count==0) objects
401 core::list<u16> objects_to_remove;
402 for(core::map<u16, ServerActiveObject*>::Iterator
403 i = m_active_objects.getIterator();
404 i.atEnd()==false; i++)
406 u16 id = i.getNode()->getKey();
407 ServerActiveObject* obj = i.getNode()->getValue();
408 // This shouldn't happen but check it
411 dstream<<"WARNING: NULL object found in ServerEnvironment"
412 <<" while finding removed objects. id="<<id<<std::endl;
413 // Id to be removed from m_active_objects
414 objects_to_remove.push_back(id);
419 // If not m_removed, don't remove.
420 if(obj->m_removed == false)
424 // Id to be removed from m_active_objects
425 objects_to_remove.push_back(id);
428 // Remove references from m_active_objects
429 for(core::list<u16>::Iterator i = objects_to_remove.begin();
430 i != objects_to_remove.end(); i++)
432 m_active_objects.remove(*i);
439 m_random_spawn_timer -= dtime;
440 if(m_random_spawn_timer < 0)
442 m_random_spawn_timer += myrand_range(2.0, 20.0);
444 /*TestSAO *obj = new TestSAO(0,
445 v3f(myrand_range(-2*BS,2*BS), BS*5, myrand_range(-2*BS,2*BS)));*/
448 Create a Lua ServerActiveObject somewhere near the origin
450 LuaSAO *obj = new LuaSAO(this, 0,
451 v3f(myrand_range(-2*BS,2*BS),
452 myrand_range(2*BS,9*BS),
453 myrand_range(-2*BS,2*BS))
457 Select a random type for it
459 std::string objectdir = porting::getDataPath("luaobjects");
460 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(objectdir);
461 u32 selected_i = myrand_range(0, dirlist.size()-1);
462 std::string selected_name = "";
463 selected_name = dirlist[selected_i].name;
464 /*for(u32 i=0; i<dirlist.size(); i++)*/
466 dstream<<"ServerEnvironment: Selected script name \""<<selected_name
467 <<"\" for new lua object"<<std::endl;
470 Load the scripts for the type
472 obj->loadScripts(selected_name.c_str());
474 // Add the object to the environment
475 addActiveObject(obj);
479 ServerActiveObject* ServerEnvironment::getActiveObject(u16 id)
481 core::map<u16, ServerActiveObject*>::Node *n;
482 n = m_active_objects.find(id);
485 return n->getValue();
488 bool isFreeServerActiveObjectId(u16 id,
489 core::map<u16, ServerActiveObject*> &objects)
494 for(core::map<u16, ServerActiveObject*>::Iterator
495 i = objects.getIterator();
496 i.atEnd()==false; i++)
498 if(i.getNode()->getKey() == id)
504 u16 getFreeServerActiveObjectId(
505 core::map<u16, ServerActiveObject*> &objects)
510 if(isFreeServerActiveObjectId(new_id, objects))
520 u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
523 if(object->getId() == 0)
525 u16 new_id = getFreeServerActiveObjectId(m_active_objects);
528 dstream<<"WARNING: ServerEnvironment::addActiveObject(): "
529 <<"no free ids available"<<std::endl;
533 object->setId(new_id);
535 if(isFreeServerActiveObjectId(object->getId(), m_active_objects) == false)
537 dstream<<"WARNING: ServerEnvironment::addActiveObject(): "
538 <<"id is not free ("<<object->getId()<<")"<<std::endl;
542 dstream<<"INGO: ServerEnvironment::addActiveObject(): "
543 <<"added (id="<<object->getId()<<")"<<std::endl;
544 m_active_objects.insert(object->getId(), object);
545 return object->getId();
549 Finds out what new objects have been added to
550 inside a radius around a position
552 void ServerEnvironment::getAddedActiveObjects(v3s16 pos, s16 radius,
553 core::map<u16, bool> ¤t_objects,
554 core::map<u16, bool> &added_objects)
556 v3f pos_f = intToFloat(pos, BS);
557 f32 radius_f = radius * BS;
559 Go through the object list,
560 - discard m_removed objects,
561 - discard objects that are too far away,
562 - discard objects that are found in current_objects.
563 - add remaining objects to added_objects
565 for(core::map<u16, ServerActiveObject*>::Iterator
566 i = m_active_objects.getIterator();
567 i.atEnd()==false; i++)
569 u16 id = i.getNode()->getKey();
571 ServerActiveObject *object = i.getNode()->getValue();
574 // Discard if removed
575 if(object->m_removed)
577 // Discard if too far
578 f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f);
579 if(distance_f > radius_f)
581 // Discard if already on current_objects
582 core::map<u16, bool>::Node *n;
583 n = current_objects.find(id);
586 // Add to added_objects
587 added_objects.insert(id, false);
592 Finds out what objects have been removed from
593 inside a radius around a position
595 void ServerEnvironment::getRemovedActiveObjects(v3s16 pos, s16 radius,
596 core::map<u16, bool> ¤t_objects,
597 core::map<u16, bool> &removed_objects)
599 v3f pos_f = intToFloat(pos, BS);
600 f32 radius_f = radius * BS;
602 Go through current_objects; object is removed if:
603 - object is not found in m_active_objects (this is actually an
604 error condition; objects should be set m_removed=true and removed
605 only after all clients have been informed about removal), or
606 - object has m_removed=true, or
607 - object is too far away
609 for(core::map<u16, bool>::Iterator
610 i = current_objects.getIterator();
611 i.atEnd()==false; i++)
613 u16 id = i.getNode()->getKey();
614 ServerActiveObject *object = getActiveObject(id);
617 dstream<<"WARNING: ServerEnvironment::getRemovedActiveObjects():"
618 <<" object in current_objects is NULL"<<std::endl;
620 else if(object->m_removed == false)
622 f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f);
623 /*dstream<<"removed == false"
624 <<"distance_f = "<<distance_f
625 <<", radius_f = "<<radius_f<<std::endl;*/
626 if(distance_f < radius_f)
632 removed_objects.insert(id, false);
636 ActiveObjectMessage ServerEnvironment::getActiveObjectMessage()
638 if(m_active_object_messages.size() == 0)
639 return ActiveObjectMessage(0);
641 return m_active_object_messages.pop_front();
650 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr):
658 ClientEnvironment::~ClientEnvironment()
660 // delete active objects
661 for(core::map<u16, ClientActiveObject*>::Iterator
662 i = m_active_objects.getIterator();
663 i.atEnd()==false; i++)
665 delete i.getNode()->getValue();
672 void ClientEnvironment::addPlayer(Player *player)
674 DSTACK(__FUNCTION_NAME);
676 It is a failure if player is local and there already is a local
679 assert(!(player->isLocal() == true && getLocalPlayer() != NULL));
681 Environment::addPlayer(player);
684 LocalPlayer * ClientEnvironment::getLocalPlayer()
686 for(core::list<Player*>::Iterator i = m_players.begin();
687 i != m_players.end(); i++)
690 if(player->isLocal())
691 return (LocalPlayer*)player;
696 void ClientEnvironment::step(float dtime)
698 DSTACK(__FUNCTION_NAME);
701 bool free_move = g_settings.getBool("free_move");
702 bool footprints = g_settings.getBool("footprints");
705 //TimeTaker timer("Client m_map->timerUpdate()", g_device);
706 m_map->timerUpdate(dtime);
710 Get the speed the player is going
712 f32 player_speed = 0.001; // just some small value
713 LocalPlayer *lplayer = getLocalPlayer();
715 player_speed = lplayer->getSpeed().getLength();
718 Maximum position increment
720 //f32 position_max_increment = 0.05*BS;
721 f32 position_max_increment = 0.1*BS;
723 // Maximum time increment (for collision detection etc)
724 // time = distance / speed
725 f32 dtime_max_increment = position_max_increment / player_speed;
727 // Maximum time increment is 10ms or lower
728 if(dtime_max_increment > 0.01)
729 dtime_max_increment = 0.01;
731 // Don't allow overly huge dtime
735 f32 dtime_downcount = dtime;
738 Stuff that has a maximum time increment
747 if(dtime_downcount > dtime_max_increment)
748 dtime_part = dtime_max_increment;
750 dtime_part = dtime_downcount;
751 dtime_downcount -= dtime_part;
758 Player *player = getLocalPlayer();
760 v3f playerpos = player->getPosition();
763 if(free_move == false)
766 v3f speed = player->getSpeed();
767 if(player->swimming_up == false)
768 speed.Y -= 9.81 * BS * dtime_part * 2;
771 if(player->in_water_stable || player->in_water)
773 f32 max_down = 2.0*BS;
774 if(speed.Y < -max_down) speed.Y = -max_down;
777 if(speed.getLength() > max)
779 speed = speed / speed.getLength() * max;
783 player->setSpeed(speed);
788 This also does collision detection.
790 player->move(dtime_part, *m_map, position_max_increment);
793 while(dtime_downcount > 0.001);
795 //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
798 Stuff that can be done in an arbitarily large dtime
800 for(core::list<Player*>::Iterator i = m_players.begin();
801 i != m_players.end(); i++)
804 v3f playerpos = player->getPosition();
807 Handle non-local players
809 if(player->isLocal() == false)
812 player->move(dtime, *m_map, 100*BS);
814 // Update lighting on remote players on client
815 u8 light = LIGHT_MAX;
818 v3s16 p = floatToInt(playerpos + v3f(0,BS+BS/2,0), BS);
819 MapNode n = m_map->getNode(p);
820 light = n.getLightBlend(m_daynight_ratio);
822 catch(InvalidPositionException &e) {}
823 player->updateLight(light);
827 Add footsteps to grass
831 // Get node that is at BS/4 under player
832 v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS);
834 MapNode n = m_map->getNode(bottompos);
835 if(n.d == CONTENT_GRASS)
837 n.d = CONTENT_GRASS_FOOTSTEPS;
838 m_map->setNode(bottompos, n);
839 // Update mesh on client
840 if(m_map->mapType() == MAPTYPE_CLIENT)
842 v3s16 p_blocks = getNodeBlockPos(bottompos);
843 MapBlock *b = m_map->getBlockNoCreate(p_blocks);
844 b->updateMesh(m_daynight_ratio);
848 catch(InvalidPositionException &e)
857 for(core::map<u16, ClientActiveObject*>::Iterator
858 i = m_active_objects.getIterator();
859 i.atEnd()==false; i++)
861 ClientActiveObject* obj = i.getNode()->getValue();
867 void ClientEnvironment::updateMeshes(v3s16 blockpos)
869 m_map->updateMeshes(blockpos, m_daynight_ratio);
872 void ClientEnvironment::expireMeshes(bool only_daynight_diffed)
874 m_map->expireMeshes(only_daynight_diffed);
877 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
879 core::map<u16, ClientActiveObject*>::Node *n;
880 n = m_active_objects.find(id);
883 return n->getValue();
886 bool isFreeClientActiveObjectId(u16 id,
887 core::map<u16, ClientActiveObject*> &objects)
892 for(core::map<u16, ClientActiveObject*>::Iterator
893 i = objects.getIterator();
894 i.atEnd()==false; i++)
896 if(i.getNode()->getKey() == id)
902 u16 getFreeClientActiveObjectId(
903 core::map<u16, ClientActiveObject*> &objects)
908 if(isFreeClientActiveObjectId(new_id, objects))
918 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
921 if(object->getId() == 0)
923 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
926 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
927 <<"no free ids available"<<std::endl;
931 object->setId(new_id);
933 if(isFreeClientActiveObjectId(object->getId(), m_active_objects) == false)
935 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
936 <<"id is not free ("<<object->getId()<<")"<<std::endl;
940 dstream<<"INGO: ClientEnvironment::addActiveObject(): "
941 <<"added (id="<<object->getId()<<")"<<std::endl;
942 m_active_objects.insert(object->getId(), object);
943 object->addToScene(m_smgr);
944 return object->getId();
947 void ClientEnvironment::addActiveObject(u16 id, u8 type,
948 const std::string &init_data)
950 ClientActiveObject* obj = ClientActiveObject::create(type);
953 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
954 <<"id="<<id<<" type="<<type<<": Couldn't create object"
961 addActiveObject(obj);
963 obj->initialize(init_data);
966 void ClientEnvironment::removeActiveObject(u16 id)
968 dstream<<"ClientEnvironment::removeActiveObject(): "
969 <<"id="<<id<<std::endl;
970 ClientActiveObject* obj = getActiveObject(id);
973 dstream<<"WARNING: ClientEnvironment::removeActiveObject(): "
974 <<"id="<<id<<" not found"<<std::endl;
977 obj->removeFromScene();
979 m_active_objects.remove(id);
982 void ClientEnvironment::processActiveObjectMessage(u16 id,
983 const std::string &data)
985 ClientActiveObject* obj = getActiveObject(id);
988 dstream<<"WARNING: ClientEnvironment::processActiveObjectMessage():"
989 <<" got message for id="<<id<<", which doesn't exist."
993 obj->processMessage(data);
996 #endif // #ifndef SERVER