]> git.lizzy.rs Git - minetest.git/blob - src/environment.cpp
fixed a bit
[minetest.git] / src / environment.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "environment.h"
21 #include "filesys.h"
22 #include "porting.h"
23
24 Environment::Environment()
25 {
26         m_daynight_ratio = 0.5;
27 }
28
29 Environment::~Environment()
30 {
31         // Deallocate players
32         for(core::list<Player*>::Iterator i = m_players.begin();
33                         i != m_players.end(); i++)
34         {
35                 delete (*i);
36         }
37 }
38
39 void Environment::addPlayer(Player *player)
40 {
41         DSTACK(__FUNCTION_NAME);
42         /*
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
46         */
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);
52         // Add.
53         m_players.push_back(player);
54 }
55
56 void Environment::removePlayer(u16 peer_id)
57 {
58         DSTACK(__FUNCTION_NAME);
59 re_search:
60         for(core::list<Player*>::Iterator i = m_players.begin();
61                         i != m_players.end(); i++)
62         {
63                 Player *player = *i;
64                 if(player->peer_id != peer_id)
65                         continue;
66                 
67                 delete player;
68                 m_players.erase(i);
69                 // See if there is an another one
70                 // (shouldn't be, but just to be sure)
71                 goto re_search;
72         }
73 }
74
75 Player * Environment::getPlayer(u16 peer_id)
76 {
77         for(core::list<Player*>::Iterator i = m_players.begin();
78                         i != m_players.end(); i++)
79         {
80                 Player *player = *i;
81                 if(player->peer_id == peer_id)
82                         return player;
83         }
84         return NULL;
85 }
86
87 Player * Environment::getPlayer(const char *name)
88 {
89         for(core::list<Player*>::Iterator i = m_players.begin();
90                         i != m_players.end(); i++)
91         {
92                 Player *player = *i;
93                 if(strcmp(player->getName(), name) == 0)
94                         return player;
95         }
96         return NULL;
97 }
98
99 Player * Environment::getRandomConnectedPlayer()
100 {
101         core::list<Player*> connected_players = getPlayers(true);
102         u32 chosen_one = myrand() % connected_players.size();
103         u32 j = 0;
104         for(core::list<Player*>::Iterator
105                         i = connected_players.begin();
106                         i != connected_players.end(); i++)
107         {
108                 if(j == chosen_one)
109                 {
110                         Player *player = *i;
111                         return player;
112                 }
113                 j++;
114         }
115         return NULL;
116 }
117
118 Player * Environment::getNearestConnectedPlayer(v3f pos)
119 {
120         core::list<Player*> connected_players = getPlayers(true);
121         f32 nearest_d = 0;
122         Player *nearest_player = NULL;
123         for(core::list<Player*>::Iterator
124                         i = connected_players.begin();
125                         i != connected_players.end(); i++)
126         {
127                 Player *player = *i;
128                 f32 d = player->getPosition().getDistanceFrom(pos);
129                 if(d < nearest_d || nearest_player == NULL)
130                 {
131                         nearest_d = d;
132                         nearest_player = player;
133                 }
134         }
135         return nearest_player;
136 }
137
138 core::list<Player*> Environment::getPlayers()
139 {
140         return m_players;
141 }
142
143 core::list<Player*> Environment::getPlayers(bool ignore_disconnected)
144 {
145         core::list<Player*> newlist;
146         for(core::list<Player*>::Iterator
147                         i = m_players.begin();
148                         i != m_players.end(); i++)
149         {
150                 Player *player = *i;
151                 
152                 if(ignore_disconnected)
153                 {
154                         // Ignore disconnected players
155                         if(player->peer_id == 0)
156                                 continue;
157                 }
158
159                 newlist.push_back(player);
160         }
161         return newlist;
162 }
163
164 void Environment::printPlayers(std::ostream &o)
165 {
166         o<<"Players in environment:"<<std::endl;
167         for(core::list<Player*>::Iterator i = m_players.begin();
168                         i != m_players.end(); i++)
169         {
170                 Player *player = *i;
171                 o<<"Player peer_id="<<player->peer_id<<std::endl;
172         }
173 }
174
175 void Environment::setDayNightRatio(u32 r)
176 {
177         m_daynight_ratio = r;
178 }
179
180 u32 Environment::getDayNightRatio()
181 {
182         return m_daynight_ratio;
183 }
184
185 /*
186         ServerEnvironment
187 */
188
189 ServerEnvironment::ServerEnvironment(ServerMap *map, Server *server):
190         m_map(map),
191         m_server(server),
192         m_random_spawn_timer(3),
193         m_send_recommended_timer(0)
194 {
195 }
196
197 ServerEnvironment::~ServerEnvironment()
198 {
199         // Drop/delete map
200         m_map->drop();
201 }
202
203 void ServerEnvironment::serializePlayers(const std::string &savedir)
204 {
205         std::string players_path = savedir + "/players";
206         fs::CreateDir(players_path);
207
208         core::map<Player*, bool> saved_players;
209
210         std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
211         for(u32 i=0; i<player_files.size(); i++)
212         {
213                 if(player_files[i].dir)
214                         continue;
215                 
216                 // Full path to this file
217                 std::string path = players_path + "/" + player_files[i].name;
218
219                 //dstream<<"Checking player file "<<path<<std::endl;
220
221                 // Load player to see what is its name
222                 ServerRemotePlayer testplayer;
223                 {
224                         // Open file and deserialize
225                         std::ifstream is(path.c_str(), std::ios_base::binary);
226                         if(is.good() == false)
227                         {
228                                 dstream<<"Failed to read "<<path<<std::endl;
229                                 continue;
230                         }
231                         testplayer.deSerialize(is);
232                 }
233
234                 //dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
235                 
236                 // Search for the player
237                 std::string playername = testplayer.getName();
238                 Player *player = getPlayer(playername.c_str());
239                 if(player == NULL)
240                 {
241                         dstream<<"Didn't find matching player, ignoring file "<<path<<std::endl;
242                         continue;
243                 }
244
245                 //dstream<<"Found matching player, overwriting."<<std::endl;
246
247                 // OK, found. Save player there.
248                 {
249                         // Open file and serialize
250                         std::ofstream os(path.c_str(), std::ios_base::binary);
251                         if(os.good() == false)
252                         {
253                                 dstream<<"Failed to overwrite "<<path<<std::endl;
254                                 continue;
255                         }
256                         player->serialize(os);
257                         saved_players.insert(player, true);
258                 }
259         }
260
261         for(core::list<Player*>::Iterator i = m_players.begin();
262                         i != m_players.end(); i++)
263         {
264                 Player *player = *i;
265                 if(saved_players.find(player) != NULL)
266                 {
267                         /*dstream<<"Player "<<player->getName()
268                                         <<" was already saved."<<std::endl;*/
269                         continue;
270                 }
271                 std::string playername = player->getName();
272                 // Don't save unnamed player
273                 if(playername == "")
274                 {
275                         //dstream<<"Not saving unnamed player."<<std::endl;
276                         continue;
277                 }
278                 /*
279                         Find a sane filename
280                 */
281                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false)
282                         playername = "player";
283                 std::string path = players_path + "/" + playername;
284                 bool found = false;
285                 for(u32 i=0; i<1000; i++)
286                 {
287                         if(fs::PathExists(path) == false)
288                         {
289                                 found = true;
290                                 break;
291                         }
292                         path = players_path + "/" + playername + itos(i);
293                 }
294                 if(found == false)
295                 {
296                         dstream<<"WARNING: Didn't find free file for player"<<std::endl;
297                         continue;
298                 }
299
300                 {
301                         /*dstream<<"Saving player "<<player->getName()<<" to "
302                                         <<path<<std::endl;*/
303                         // Open file and serialize
304                         std::ofstream os(path.c_str(), std::ios_base::binary);
305                         if(os.good() == false)
306                         {
307                                 dstream<<"WARNING: Failed to overwrite "<<path<<std::endl;
308                                 continue;
309                         }
310                         player->serialize(os);
311                         saved_players.insert(player, true);
312                 }
313         }
314
315         //dstream<<"Saved "<<saved_players.size()<<" players."<<std::endl;
316 }
317
318 void ServerEnvironment::deSerializePlayers(const std::string &savedir)
319 {
320         std::string players_path = savedir + "/players";
321
322         core::map<Player*, bool> saved_players;
323
324         std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
325         for(u32 i=0; i<player_files.size(); i++)
326         {
327                 if(player_files[i].dir)
328                         continue;
329                 
330                 // Full path to this file
331                 std::string path = players_path + "/" + player_files[i].name;
332
333                 dstream<<"Checking player file "<<path<<std::endl;
334
335                 // Load player to see what is its name
336                 ServerRemotePlayer testplayer;
337                 {
338                         // Open file and deserialize
339                         std::ifstream is(path.c_str(), std::ios_base::binary);
340                         if(is.good() == false)
341                         {
342                                 dstream<<"Failed to read "<<path<<std::endl;
343                                 continue;
344                         }
345                         testplayer.deSerialize(is);
346                 }
347
348                 dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
349                 
350                 // Search for the player
351                 std::string playername = testplayer.getName();
352                 Player *player = getPlayer(playername.c_str());
353                 bool newplayer = false;
354                 if(player == NULL)
355                 {
356                         dstream<<"Is a new player"<<std::endl;
357                         player = new ServerRemotePlayer();
358                         newplayer = true;
359                 }
360
361                 // Load player
362                 {
363                         dstream<<"Reading player "<<testplayer.getName()<<" from "
364                                         <<path<<std::endl;
365                         // Open file and deserialize
366                         std::ifstream is(path.c_str(), std::ios_base::binary);
367                         if(is.good() == false)
368                         {
369                                 dstream<<"Failed to read "<<path<<std::endl;
370                                 continue;
371                         }
372                         player->deSerialize(is);
373                 }
374
375                 if(newplayer)
376                         addPlayer(player);
377         }
378 }
379
380 void ServerEnvironment::step(float dtime)
381 {
382         DSTACK(__FUNCTION_NAME);
383
384         // Get some settings
385         //bool free_move = g_settings.getBool("free_move");
386         bool footprints = g_settings.getBool("footprints");
387
388         {
389                 //TimeTaker timer("Server m_map->timerUpdate()", g_device);
390                 m_map->timerUpdate(dtime);
391         }
392
393         /*
394                 Handle players
395         */
396         for(core::list<Player*>::Iterator i = m_players.begin();
397                         i != m_players.end(); i++)
398         {
399                 Player *player = *i;
400                 v3f playerpos = player->getPosition();
401                 
402                 // Move
403                 player->move(dtime, *m_map, 100*BS);
404                 
405                 /*
406                         Add footsteps to grass
407                 */
408                 if(footprints)
409                 {
410                         // Get node that is at BS/4 under player
411                         v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS);
412                         try{
413                                 MapNode n = m_map->getNode(bottompos);
414                                 if(n.d == CONTENT_GRASS)
415                                 {
416                                         n.d = CONTENT_GRASS_FOOTSTEPS;
417                                         m_map->setNode(bottompos, n);
418                                 }
419                         }
420                         catch(InvalidPositionException &e)
421                         {
422                         }
423                 }
424         }
425         
426         /*
427                 Step active objects
428         */
429
430         bool send_recommended = false;
431         m_send_recommended_timer += dtime;
432         if(m_send_recommended_timer > 0.2)
433         {
434                 m_send_recommended_timer = 0;
435                 send_recommended = true;
436         }
437
438         for(core::map<u16, ServerActiveObject*>::Iterator
439                         i = m_active_objects.getIterator();
440                         i.atEnd()==false; i++)
441         {
442                 ServerActiveObject* obj = i.getNode()->getValue();
443                 // Step object, putting messages directly to the queue
444                 obj->step(dtime, m_active_object_messages, send_recommended);
445         }
446
447         /*
448                 Remove objects that satisfy (m_removed && m_known_by_count==0)
449         */
450         {
451                 core::list<u16> objects_to_remove;
452                 for(core::map<u16, ServerActiveObject*>::Iterator
453                                 i = m_active_objects.getIterator();
454                                 i.atEnd()==false; i++)
455                 {
456                         u16 id = i.getNode()->getKey();
457                         ServerActiveObject* obj = i.getNode()->getValue();
458                         // This shouldn't happen but check it
459                         if(obj == NULL)
460                         {
461                                 dstream<<"WARNING: NULL object found in ServerEnvironment"
462                                                 <<" while finding removed objects. id="<<id<<std::endl;
463                                 // Id to be removed from m_active_objects
464                                 objects_to_remove.push_back(id);
465                                 continue;
466                         }
467                         // If not m_removed, don't remove.
468                         if(obj->m_removed == false)
469                                 continue;
470                         // Delete static data from block
471                         if(obj->m_static_exists)
472                         {
473                                 MapBlock *block = m_map->getBlockNoCreateNoEx(obj->m_static_block);
474                                 if(block)
475                                 {
476                                         block->m_static_objects.remove(id);
477                                         block->setChangedFlag();
478                                 }
479                         }
480                         // If m_known_by_count > 0, don't actually remove.
481                         if(obj->m_known_by_count > 0)
482                                 continue;
483                         // Delete
484                         delete obj;
485                         // Id to be removed from m_active_objects
486                         objects_to_remove.push_back(id);
487                 }
488                 // Remove references from m_active_objects
489                 for(core::list<u16>::Iterator i = objects_to_remove.begin();
490                                 i != objects_to_remove.end(); i++)
491                 {
492                         m_active_objects.remove(*i);
493                 }
494         }
495         
496
497         const s16 to_active_max_blocks = 3;
498         const f32 to_static_max_f = (to_active_max_blocks+1)*MAP_BLOCKSIZE*BS;
499
500         /*
501                 Convert stored objects from blocks near the players to active.
502         */
503         for(core::list<Player*>::Iterator i = m_players.begin();
504                         i != m_players.end(); i++)
505         {
506                 Player *player = *i;
507                 v3f playerpos = player->getPosition();
508                 
509                 v3s16 blockpos0 = getNodeBlockPos(floatToInt(playerpos, BS));
510                 v3s16 bpmin = blockpos0 - v3s16(1,1,1)*to_active_max_blocks;
511                 v3s16 bpmax = blockpos0 + v3s16(1,1,1)*to_active_max_blocks;
512                 // Loop through all nearby blocks
513                 for(s16 x=bpmin.X; x<=bpmax.X; x++)
514                 for(s16 y=bpmin.Y; y<=bpmax.Y; y++)
515                 for(s16 z=bpmin.Z; z<=bpmax.Z; z++)
516                 {
517                         v3s16 blockpos(x,y,z);
518                         MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
519                         if(block==NULL)
520                                 continue;
521                         // Ignore if no stored objects (to not set changed flag)
522                         if(block->m_static_objects.m_stored.size() == 0)
523                                 continue;
524                         // This will contain the leftovers of the stored list
525                         core::list<StaticObject> new_stored;
526                         // Loop through stored static objects
527                         for(core::list<StaticObject>::Iterator
528                                         i = block->m_static_objects.m_stored.begin();
529                                         i != block->m_static_objects.m_stored.end(); i++)
530                         {
531                                 dstream<<"INFO: Server: Creating an active object from "
532                                                 <<"static data"<<std::endl;
533                                 StaticObject &s_obj = *i;
534                                 // Create an active object from the data
535                                 ServerActiveObject *obj = ServerActiveObject::create
536                                                 (s_obj.type, this, 0, s_obj.pos, s_obj.data);
537                                 if(obj==NULL)
538                                 {
539                                         // This is necessary to preserve stuff during bugs
540                                         // and errors
541                                         new_stored.push_back(s_obj);
542                                         continue;
543                                 }
544                                 // This will also add the object to the active static list
545                                 addActiveObject(obj);
546                                 //u16 id = addActiveObject(obj);
547                         }
548                         // Clear stored list
549                         block->m_static_objects.m_stored.clear();
550                         // Add leftover stuff to stored list
551                         for(core::list<StaticObject>::Iterator
552                                         i = new_stored.begin();
553                                         i != new_stored.end(); i++)
554                         {
555                                 StaticObject &s_obj = *i;
556                                 block->m_static_objects.m_stored.push_back(s_obj);
557                         }
558                         block->setChangedFlag();
559                 }
560         }
561
562         /*
563                 Convert objects that are far away from all the players to static.
564         */
565         {
566                 core::list<u16> objects_to_remove;
567                 for(core::map<u16, ServerActiveObject*>::Iterator
568                                 i = m_active_objects.getIterator();
569                                 i.atEnd()==false; i++)
570                 {
571                         ServerActiveObject* obj = i.getNode()->getValue();
572                         u16 id = i.getNode()->getKey();
573                         v3f objectpos = obj->getBasePosition();
574
575                         // This shouldn't happen but check it
576                         if(obj == NULL)
577                         {
578                                 dstream<<"WARNING: NULL object found in ServerEnvironment"
579                                                 <<std::endl;
580                                 continue;
581                         }
582                         // If known by some client, don't convert to static.
583                         if(obj->m_known_by_count > 0)
584                                 continue;
585
586                         // If close to some player, don't convert to static.
587                         bool close_to_player = false;
588                         for(core::list<Player*>::Iterator i = m_players.begin();
589                                         i != m_players.end(); i++)
590                         {
591                                 Player *player = *i;
592                                 v3f playerpos = player->getPosition();
593                                 f32 d = playerpos.getDistanceFrom(objectpos);
594                                 if(d < to_static_max_f)
595                                 {
596                                         close_to_player = true;
597                                         break;
598                                 }
599                         }
600
601                         if(close_to_player)
602                                 continue;
603
604                         /*
605                                 Update the static data and remove the active object.
606                         */
607
608                         // Delete old static object
609                         MapBlock *oldblock = NULL;
610                         if(obj->m_static_exists)
611                         {
612                                 MapBlock *block = m_map->getBlockNoCreateNoEx(obj->m_static_block);
613                                 if(block)
614                                 {
615                                         block->m_static_objects.remove(id);
616                                         oldblock = block;
617                                 }
618                         }
619                         // Add new static object
620                         std::string staticdata = obj->getStaticData();
621                         StaticObject s_obj(obj->getType(), objectpos, staticdata);
622                         // Add to the block where the object is located in
623                         v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
624                         MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
625                         if(block)
626                         {
627                                 block->m_static_objects.insert(0, s_obj);
628                                 block->setChangedFlag();
629                                 obj->m_static_exists = true;
630                                 obj->m_static_block = block->getPos();
631                         }
632                         // If not possible, add back to previous block
633                         else if(oldblock)
634                         {
635                                 oldblock->m_static_objects.insert(0, s_obj);
636                                 oldblock->setChangedFlag();
637                                 obj->m_static_exists = true;
638                                 obj->m_static_block = oldblock->getPos();
639                         }
640                         else{
641                                 dstream<<"WARNING: Server: Could not find a block for "
642                                                 <<"storing static object"<<std::endl;
643                                 obj->m_static_exists = false;
644                                 continue;
645                         }
646                         // Delete active object
647                         dstream<<"INFO: Server: Stored static data. Deleting object."
648                                         <<std::endl;
649                         delete obj;
650                         // Id to be removed from m_active_objects
651                         objects_to_remove.push_back(id);
652                 }
653                 // Remove references from m_active_objects
654                 for(core::list<u16>::Iterator i = objects_to_remove.begin();
655                                 i != objects_to_remove.end(); i++)
656                 {
657                         m_active_objects.remove(*i);
658                 }
659         }
660
661         if(g_settings.getBool("enable_experimental"))
662         {
663
664         /*
665                 TEST CODE
666         */
667 #if 1
668         m_random_spawn_timer -= dtime;
669         if(m_random_spawn_timer < 0)
670         {
671                 //m_random_spawn_timer += myrand_range(2.0, 20.0);
672                 //m_random_spawn_timer += 2.0;
673                 m_random_spawn_timer += 200.0;
674
675                 /*
676                         Find some position
677                 */
678
679                 /*v2s16 p2d(myrand_range(-5,5), myrand_range(-5,5));
680                 s16 y = 1 + getServerMap().findGroundLevel(p2d);
681                 v3f pos(p2d.X*BS,y*BS,p2d.Y*BS);*/
682                 
683                 Player *player = getRandomConnectedPlayer();
684                 v3f pos(0,0,0);
685                 if(player)
686                         pos = player->getPosition();
687                 pos += v3f(
688                         myrand_range(-3,3)*BS,
689                         0,
690                         myrand_range(-3,3)*BS
691                 );
692
693                 /*
694                         Create a ServerActiveObject
695                 */
696
697                 //TestSAO *obj = new TestSAO(this, 0, pos);
698                 //ServerActiveObject *obj = new ItemSAO(this, 0, pos, "CraftItem Stick 1");
699                 ServerActiveObject *obj = new RatSAO(this, 0, pos);
700                 addActiveObject(obj);
701         }
702 #endif
703
704         } // enable_experimental
705 }
706
707 ServerActiveObject* ServerEnvironment::getActiveObject(u16 id)
708 {
709         core::map<u16, ServerActiveObject*>::Node *n;
710         n = m_active_objects.find(id);
711         if(n == NULL)
712                 return NULL;
713         return n->getValue();
714 }
715
716 bool isFreeServerActiveObjectId(u16 id,
717                 core::map<u16, ServerActiveObject*> &objects)
718 {
719         if(id == 0)
720                 return false;
721         
722         for(core::map<u16, ServerActiveObject*>::Iterator
723                         i = objects.getIterator();
724                         i.atEnd()==false; i++)
725         {
726                 if(i.getNode()->getKey() == id)
727                         return false;
728         }
729         return true;
730 }
731
732 u16 getFreeServerActiveObjectId(
733                 core::map<u16, ServerActiveObject*> &objects)
734 {
735         u16 new_id = 1;
736         for(;;)
737         {
738                 if(isFreeServerActiveObjectId(new_id, objects))
739                         return new_id;
740                 
741                 if(new_id == 65535)
742                         return 0;
743
744                 new_id++;
745         }
746 }
747
748 u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
749 {
750         assert(object);
751         if(object->getId() == 0)
752         {
753                 u16 new_id = getFreeServerActiveObjectId(m_active_objects);
754                 if(new_id == 0)
755                 {
756                         dstream<<"WARNING: ServerEnvironment::addActiveObject(): "
757                                         <<"no free ids available"<<std::endl;
758                         delete object;
759                         return 0;
760                 }
761                 object->setId(new_id);
762         }
763         if(isFreeServerActiveObjectId(object->getId(), m_active_objects) == false)
764         {
765                 dstream<<"WARNING: ServerEnvironment::addActiveObject(): "
766                                 <<"id is not free ("<<object->getId()<<")"<<std::endl;
767                 delete object;
768                 return 0;
769         }
770         dstream<<"INGO: ServerEnvironment::addActiveObject(): "
771                         <<"added (id="<<object->getId()<<")"<<std::endl;
772                         
773         m_active_objects.insert(object->getId(), object);
774
775         // Add static object to active static list of the block
776         v3f objectpos = object->getBasePosition();
777         std::string staticdata = object->getStaticData();
778         StaticObject s_obj(object->getType(), objectpos, staticdata);
779         // Add to the block where the object is located in
780         v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
781         MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
782         if(block)
783         {
784                 block->m_static_objects.m_active.insert(object->getId(), s_obj);
785                 object->m_static_exists = true;
786                 object->m_static_block = blockpos;
787         }
788         else{
789                 dstream<<"WARNING: Server: Could not find a block for "
790                                 <<"storing newly added static active object"<<std::endl;
791         }
792
793         return object->getId();
794 }
795
796 /*
797         Finds out what new objects have been added to
798         inside a radius around a position
799 */
800 void ServerEnvironment::getAddedActiveObjects(v3s16 pos, s16 radius,
801                 core::map<u16, bool> &current_objects,
802                 core::map<u16, bool> &added_objects)
803 {
804         v3f pos_f = intToFloat(pos, BS);
805         f32 radius_f = radius * BS;
806         /*
807                 Go through the object list,
808                 - discard m_removed objects,
809                 - discard objects that are too far away,
810                 - discard objects that are found in current_objects.
811                 - add remaining objects to added_objects
812         */
813         for(core::map<u16, ServerActiveObject*>::Iterator
814                         i = m_active_objects.getIterator();
815                         i.atEnd()==false; i++)
816         {
817                 u16 id = i.getNode()->getKey();
818                 // Get object
819                 ServerActiveObject *object = i.getNode()->getValue();
820                 if(object == NULL)
821                         continue;
822                 // Discard if removed
823                 if(object->m_removed)
824                         continue;
825                 // Discard if too far
826                 f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f);
827                 if(distance_f > radius_f)
828                         continue;
829                 // Discard if already on current_objects
830                 core::map<u16, bool>::Node *n;
831                 n = current_objects.find(id);
832                 if(n != NULL)
833                         continue;
834                 // Add to added_objects
835                 added_objects.insert(id, false);
836         }
837 }
838
839 /*
840         Finds out what objects have been removed from
841         inside a radius around a position
842 */
843 void ServerEnvironment::getRemovedActiveObjects(v3s16 pos, s16 radius,
844                 core::map<u16, bool> &current_objects,
845                 core::map<u16, bool> &removed_objects)
846 {
847         v3f pos_f = intToFloat(pos, BS);
848         f32 radius_f = radius * BS;
849         /*
850                 Go through current_objects; object is removed if:
851                 - object is not found in m_active_objects (this is actually an
852                   error condition; objects should be set m_removed=true and removed
853                   only after all clients have been informed about removal), or
854                 - object has m_removed=true, or
855                 - object is too far away
856         */
857         for(core::map<u16, bool>::Iterator
858                         i = current_objects.getIterator();
859                         i.atEnd()==false; i++)
860         {
861                 u16 id = i.getNode()->getKey();
862                 ServerActiveObject *object = getActiveObject(id);
863                 if(object == NULL)
864                 {
865                         dstream<<"WARNING: ServerEnvironment::getRemovedActiveObjects():"
866                                         <<" object in current_objects is NULL"<<std::endl;
867                 }
868                 else if(object->m_removed == false)
869                 {
870                         f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f);
871                         /*dstream<<"removed == false"
872                                         <<"distance_f = "<<distance_f
873                                         <<", radius_f = "<<radius_f<<std::endl;*/
874                         if(distance_f < radius_f)
875                         {
876                                 // Not removed
877                                 continue;
878                         }
879                 }
880                 removed_objects.insert(id, false);
881         }
882 }
883
884 ActiveObjectMessage ServerEnvironment::getActiveObjectMessage()
885 {
886         if(m_active_object_messages.size() == 0)
887                 return ActiveObjectMessage(0);
888         
889         return m_active_object_messages.pop_front();
890 }
891
892 #ifndef SERVER
893
894 /*
895         ClientEnvironment
896 */
897
898 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr):
899         m_map(map),
900         m_smgr(smgr)
901 {
902         assert(m_map);
903         assert(m_smgr);
904 }
905
906 ClientEnvironment::~ClientEnvironment()
907 {
908         // delete active objects
909         for(core::map<u16, ClientActiveObject*>::Iterator
910                         i = m_active_objects.getIterator();
911                         i.atEnd()==false; i++)
912         {
913                 delete i.getNode()->getValue();
914         }
915
916         // Drop/delete map
917         m_map->drop();
918 }
919
920 void ClientEnvironment::addPlayer(Player *player)
921 {
922         DSTACK(__FUNCTION_NAME);
923         /*
924                 It is a failure if player is local and there already is a local
925                 player
926         */
927         assert(!(player->isLocal() == true && getLocalPlayer() != NULL));
928
929         Environment::addPlayer(player);
930 }
931
932 LocalPlayer * ClientEnvironment::getLocalPlayer()
933 {
934         for(core::list<Player*>::Iterator i = m_players.begin();
935                         i != m_players.end(); i++)
936         {
937                 Player *player = *i;
938                 if(player->isLocal())
939                         return (LocalPlayer*)player;
940         }
941         return NULL;
942 }
943
944 void ClientEnvironment::step(float dtime)
945 {
946         DSTACK(__FUNCTION_NAME);
947
948         // Get some settings
949         bool free_move = g_settings.getBool("free_move");
950         bool footprints = g_settings.getBool("footprints");
951
952         {
953                 //TimeTaker timer("Client m_map->timerUpdate()", g_device);
954                 m_map->timerUpdate(dtime);
955         }
956
957         /*
958                 Get the speed the player is going
959         */
960         f32 player_speed = 0.001; // just some small value
961         LocalPlayer *lplayer = getLocalPlayer();
962         if(lplayer)
963                 player_speed = lplayer->getSpeed().getLength();
964         
965         /*
966                 Maximum position increment
967         */
968         //f32 position_max_increment = 0.05*BS;
969         f32 position_max_increment = 0.1*BS;
970
971         // Maximum time increment (for collision detection etc)
972         // time = distance / speed
973         f32 dtime_max_increment = position_max_increment / player_speed;
974         
975         // Maximum time increment is 10ms or lower
976         if(dtime_max_increment > 0.01)
977                 dtime_max_increment = 0.01;
978         
979         // Don't allow overly huge dtime
980         if(dtime > 0.5)
981                 dtime = 0.5;
982         
983         f32 dtime_downcount = dtime;
984
985         /*
986                 Stuff that has a maximum time increment
987         */
988
989         u32 loopcount = 0;
990         do
991         {
992                 loopcount++;
993
994                 f32 dtime_part;
995                 if(dtime_downcount > dtime_max_increment)
996                 {
997                         dtime_part = dtime_max_increment;
998                         dtime_downcount -= dtime_part;
999                 }
1000                 else
1001                 {
1002                         dtime_part = dtime_downcount;
1003                         /*
1004                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
1005                                 when dtime_part is so small that dtime_downcount -= dtime_part
1006                                 does nothing
1007                         */
1008                         dtime_downcount = 0;
1009                 }
1010                 
1011                 /*
1012                         Handle local player
1013                 */
1014                 
1015                 {
1016                         Player *player = getLocalPlayer();
1017
1018                         v3f playerpos = player->getPosition();
1019                         
1020                         // Apply physics
1021                         if(free_move == false)
1022                         {
1023                                 // Gravity
1024                                 v3f speed = player->getSpeed();
1025                                 if(player->swimming_up == false)
1026                                         speed.Y -= 9.81 * BS * dtime_part * 2;
1027
1028                                 // Water resistance
1029                                 if(player->in_water_stable || player->in_water)
1030                                 {
1031                                         f32 max_down = 2.0*BS;
1032                                         if(speed.Y < -max_down) speed.Y = -max_down;
1033
1034                                         f32 max = 2.5*BS;
1035                                         if(speed.getLength() > max)
1036                                         {
1037                                                 speed = speed / speed.getLength() * max;
1038                                         }
1039                                 }
1040
1041                                 player->setSpeed(speed);
1042                         }
1043
1044                         /*
1045                                 Move the player.
1046                                 This also does collision detection.
1047                         */
1048                         player->move(dtime_part, *m_map, position_max_increment);
1049                 }
1050         }
1051         while(dtime_downcount > 0.001);
1052                 
1053         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
1054         
1055         /*
1056                 Stuff that can be done in an arbitarily large dtime
1057         */
1058         for(core::list<Player*>::Iterator i = m_players.begin();
1059                         i != m_players.end(); i++)
1060         {
1061                 Player *player = *i;
1062                 v3f playerpos = player->getPosition();
1063                 
1064                 /*
1065                         Handle non-local players
1066                 */
1067                 if(player->isLocal() == false)
1068                 {
1069                         // Move
1070                         player->move(dtime, *m_map, 100*BS);
1071
1072                         // Update lighting on remote players on client
1073                         u8 light = LIGHT_MAX;
1074                         try{
1075                                 // Get node at head
1076                                 v3s16 p = floatToInt(playerpos + v3f(0,BS+BS/2,0), BS);
1077                                 MapNode n = m_map->getNode(p);
1078                                 light = n.getLightBlend(m_daynight_ratio);
1079                         }
1080                         catch(InvalidPositionException &e) {}
1081                         player->updateLight(light);
1082                 }
1083                 
1084                 /*
1085                         Add footsteps to grass
1086                 */
1087                 if(footprints)
1088                 {
1089                         // Get node that is at BS/4 under player
1090                         v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS);
1091                         try{
1092                                 MapNode n = m_map->getNode(bottompos);
1093                                 if(n.d == CONTENT_GRASS)
1094                                 {
1095                                         n.d = CONTENT_GRASS_FOOTSTEPS;
1096                                         m_map->setNode(bottompos, n);
1097                                         // Update mesh on client
1098                                         if(m_map->mapType() == MAPTYPE_CLIENT)
1099                                         {
1100                                                 v3s16 p_blocks = getNodeBlockPos(bottompos);
1101                                                 MapBlock *b = m_map->getBlockNoCreate(p_blocks);
1102                                                 //b->updateMesh(m_daynight_ratio);
1103                                                 b->setMeshExpired(true);
1104                                         }
1105                                 }
1106                         }
1107                         catch(InvalidPositionException &e)
1108                         {
1109                         }
1110                 }
1111         }
1112         
1113         /*
1114                 Step active objects
1115         */
1116         
1117         for(core::map<u16, ClientActiveObject*>::Iterator
1118                         i = m_active_objects.getIterator();
1119                         i.atEnd()==false; i++)
1120         {
1121                 ClientActiveObject* obj = i.getNode()->getValue();
1122                 // Step object
1123                 obj->step(dtime, this);
1124         }
1125 }
1126
1127 void ClientEnvironment::updateMeshes(v3s16 blockpos)
1128 {
1129         m_map->updateMeshes(blockpos, m_daynight_ratio);
1130 }
1131
1132 void ClientEnvironment::expireMeshes(bool only_daynight_diffed)
1133 {
1134         m_map->expireMeshes(only_daynight_diffed);
1135 }
1136
1137 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
1138 {
1139         core::map<u16, ClientActiveObject*>::Node *n;
1140         n = m_active_objects.find(id);
1141         if(n == NULL)
1142                 return NULL;
1143         return n->getValue();
1144 }
1145
1146 bool isFreeClientActiveObjectId(u16 id,
1147                 core::map<u16, ClientActiveObject*> &objects)
1148 {
1149         if(id == 0)
1150                 return false;
1151         
1152         for(core::map<u16, ClientActiveObject*>::Iterator
1153                         i = objects.getIterator();
1154                         i.atEnd()==false; i++)
1155         {
1156                 if(i.getNode()->getKey() == id)
1157                         return false;
1158         }
1159         return true;
1160 }
1161
1162 u16 getFreeClientActiveObjectId(
1163                 core::map<u16, ClientActiveObject*> &objects)
1164 {
1165         u16 new_id = 1;
1166         for(;;)
1167         {
1168                 if(isFreeClientActiveObjectId(new_id, objects))
1169                         return new_id;
1170                 
1171                 if(new_id == 65535)
1172                         return 0;
1173
1174                 new_id++;
1175         }
1176 }
1177
1178 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
1179 {
1180         assert(object);
1181         if(object->getId() == 0)
1182         {
1183                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
1184                 if(new_id == 0)
1185                 {
1186                         dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
1187                                         <<"no free ids available"<<std::endl;
1188                         delete object;
1189                         return 0;
1190                 }
1191                 object->setId(new_id);
1192         }
1193         if(isFreeClientActiveObjectId(object->getId(), m_active_objects) == false)
1194         {
1195                 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
1196                                 <<"id is not free ("<<object->getId()<<")"<<std::endl;
1197                 delete object;
1198                 return 0;
1199         }
1200         dstream<<"INGO: ClientEnvironment::addActiveObject(): "
1201                         <<"added (id="<<object->getId()<<")"<<std::endl;
1202         m_active_objects.insert(object->getId(), object);
1203         object->addToScene(m_smgr);
1204         return object->getId();
1205 }
1206
1207 void ClientEnvironment::addActiveObject(u16 id, u8 type,
1208                 const std::string &init_data)
1209 {
1210         ClientActiveObject* obj = ClientActiveObject::create(type);
1211         if(obj == NULL)
1212         {
1213                 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
1214                                 <<"id="<<id<<" type="<<type<<": Couldn't create object"
1215                                 <<std::endl;
1216                 return;
1217         }
1218         
1219         obj->setId(id);
1220
1221         addActiveObject(obj);
1222
1223         obj->initialize(init_data);
1224 }
1225
1226 void ClientEnvironment::removeActiveObject(u16 id)
1227 {
1228         dstream<<"ClientEnvironment::removeActiveObject(): "
1229                         <<"id="<<id<<std::endl;
1230         ClientActiveObject* obj = getActiveObject(id);
1231         if(obj == NULL)
1232         {
1233                 dstream<<"WARNING: ClientEnvironment::removeActiveObject(): "
1234                                 <<"id="<<id<<" not found"<<std::endl;
1235                 return;
1236         }
1237         obj->removeFromScene();
1238         delete obj;
1239         m_active_objects.remove(id);
1240 }
1241
1242 void ClientEnvironment::processActiveObjectMessage(u16 id,
1243                 const std::string &data)
1244 {
1245         ClientActiveObject* obj = getActiveObject(id);
1246         if(obj == NULL)
1247         {
1248                 dstream<<"WARNING: ClientEnvironment::processActiveObjectMessage():"
1249                                 <<" got message for id="<<id<<", which doesn't exist."
1250                                 <<std::endl;
1251                 return;
1252         }
1253         obj->processMessage(data);
1254 }
1255
1256 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
1257                 core::array<DistanceSortedActiveObject> &dest)
1258 {
1259         for(core::map<u16, ClientActiveObject*>::Iterator
1260                         i = m_active_objects.getIterator();
1261                         i.atEnd()==false; i++)
1262         {
1263                 ClientActiveObject* obj = i.getNode()->getValue();
1264
1265                 f32 d = (obj->getPosition() - origin).getLength();
1266
1267                 if(d > max_d)
1268                         continue;
1269
1270                 DistanceSortedActiveObject dso(obj, d);
1271
1272                 dest.push_back(dso);
1273         }
1274 }
1275
1276
1277 #endif // #ifndef SERVER
1278
1279