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