82671bf896e1ee3e9f6df322e28dfafb2a060ca9
[oweals/minetest.git] / src / server.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 "server.h"
21 #include "utility.h"
22 #include <iostream>
23 #include "clientserver.h"
24 #include "map.h"
25 #include "jmutexautolock.h"
26 #include "main.h"
27 #include "constants.h"
28 #include "voxel.h"
29 #include "materials.h"
30 #include "mineral.h"
31 #include "config.h"
32 #include "servercommand.h"
33 #include "filesys.h"
34 #include "content_mapnode.h"
35 #include "content_craft.h"
36 #include "content_nodemeta.h"
37 #include "mapblock.h"
38 #include "serverobject.h"
39 #include "settings.h"
40 #include "profiler.h"
41 #include "log.h"
42 #include "script.h"
43 #include "scriptapi.h"
44
45 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
46
47 #define BLOCK_EMERGE_FLAG_FROMDISK (1<<0)
48
49 class MapEditEventIgnorer
50 {
51 public:
52         MapEditEventIgnorer(bool *flag):
53                 m_flag(flag)
54         {
55                 if(*m_flag == false)
56                         *m_flag = true;
57                 else
58                         m_flag = NULL;
59         }
60
61         ~MapEditEventIgnorer()
62         {
63                 if(m_flag)
64                 {
65                         assert(*m_flag);
66                         *m_flag = false;
67                 }
68         }
69         
70 private:
71         bool *m_flag;
72 };
73
74 void * ServerThread::Thread()
75 {
76         ThreadStarted();
77
78         log_register_thread("ServerThread");
79
80         DSTACK(__FUNCTION_NAME);
81
82         BEGIN_DEBUG_EXCEPTION_HANDLER
83
84         while(getRun())
85         {
86                 try{
87                         //TimeTaker timer("AsyncRunStep() + Receive()");
88
89                         {
90                                 //TimeTaker timer("AsyncRunStep()");
91                                 m_server->AsyncRunStep();
92                         }
93                 
94                         //infostream<<"Running m_server->Receive()"<<std::endl;
95                         m_server->Receive();
96                 }
97                 catch(con::NoIncomingDataException &e)
98                 {
99                 }
100                 catch(con::PeerNotFoundException &e)
101                 {
102                         infostream<<"Server: PeerNotFoundException"<<std::endl;
103                 }
104         }
105         
106         END_DEBUG_EXCEPTION_HANDLER(errorstream)
107
108         return NULL;
109 }
110
111 void * EmergeThread::Thread()
112 {
113         ThreadStarted();
114
115         log_register_thread("EmergeThread");
116
117         DSTACK(__FUNCTION_NAME);
118
119         BEGIN_DEBUG_EXCEPTION_HANDLER
120
121         bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
122         
123         /*
124                 Get block info from queue, emerge them and send them
125                 to clients.
126
127                 After queue is empty, exit.
128         */
129         while(getRun())
130         {
131                 QueuedBlockEmerge *qptr = m_server->m_emerge_queue.pop();
132                 if(qptr == NULL)
133                         break;
134                 
135                 SharedPtr<QueuedBlockEmerge> q(qptr);
136
137                 v3s16 &p = q->pos;
138                 v2s16 p2d(p.X,p.Z);
139
140                 /*
141                         Do not generate over-limit
142                 */
143                 if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
144                 || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
145                 || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
146                 || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
147                 || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
148                 || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
149                         continue;
150                         
151                 //infostream<<"EmergeThread::Thread(): running"<<std::endl;
152
153                 //TimeTaker timer("block emerge");
154                 
155                 /*
156                         Try to emerge it from somewhere.
157
158                         If it is only wanted as optional, only loading from disk
159                         will be allowed.
160                 */
161                 
162                 /*
163                         Check if any peer wants it as non-optional. In that case it
164                         will be generated.
165
166                         Also decrement the emerge queue count in clients.
167                 */
168
169                 bool only_from_disk = true;
170
171                 {
172                         core::map<u16, u8>::Iterator i;
173                         for(i=q->peer_ids.getIterator(); i.atEnd()==false; i++)
174                         {
175                                 //u16 peer_id = i.getNode()->getKey();
176
177                                 // Check flags
178                                 u8 flags = i.getNode()->getValue();
179                                 if((flags & BLOCK_EMERGE_FLAG_FROMDISK) == false)
180                                         only_from_disk = false;
181                                 
182                         }
183                 }
184                 
185                 if(enable_mapgen_debug_info)
186                         infostream<<"EmergeThread: p="
187                                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
188                                         <<"only_from_disk="<<only_from_disk<<std::endl;
189                 
190                 ServerMap &map = ((ServerMap&)m_server->m_env->getMap());
191                         
192                 //core::map<v3s16, MapBlock*> changed_blocks;
193                 //core::map<v3s16, MapBlock*> lighting_invalidated_blocks;
194
195                 MapBlock *block = NULL;
196                 bool got_block = true;
197                 core::map<v3s16, MapBlock*> modified_blocks;
198                 
199                 /*
200                         Fetch block from map or generate a single block
201                 */
202                 {
203                         JMutexAutoLock envlock(m_server->m_env_mutex);
204                         
205                         // Load sector if it isn't loaded
206                         if(map.getSectorNoGenerateNoEx(p2d) == NULL)
207                                 //map.loadSectorFull(p2d);
208                                 map.loadSectorMeta(p2d);
209
210                         block = map.getBlockNoCreateNoEx(p);
211                         if(!block || block->isDummy() || !block->isGenerated())
212                         {
213                                 if(enable_mapgen_debug_info)
214                                         infostream<<"EmergeThread: not in memory, loading"<<std::endl;
215
216                                 // Get, load or create sector
217                                 /*ServerMapSector *sector =
218                                                 (ServerMapSector*)map.createSector(p2d);*/
219
220                                 // Load/generate block
221
222                                 /*block = map.emergeBlock(p, sector, changed_blocks,
223                                                 lighting_invalidated_blocks);*/
224
225                                 block = map.loadBlock(p);
226                                 
227                                 if(only_from_disk == false)
228                                 {
229                                         if(block == NULL || block->isGenerated() == false)
230                                         {
231                                                 if(enable_mapgen_debug_info)
232                                                         infostream<<"EmergeThread: generating"<<std::endl;
233                                                 block = map.generateBlock(p, modified_blocks);
234                                         }
235                                 }
236
237                                 if(enable_mapgen_debug_info)
238                                         infostream<<"EmergeThread: ended up with: "
239                                                         <<analyze_block(block)<<std::endl;
240
241                                 if(block == NULL)
242                                 {
243                                         got_block = false;
244                                 }
245                                 else
246                                 {
247                                         /*
248                                                 Ignore map edit events, they will not need to be
249                                                 sent to anybody because the block hasn't been sent
250                                                 to anybody
251                                         */
252                                         MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
253                                         
254                                         // Activate objects and stuff
255                                         m_server->m_env->activateBlock(block, 3600);
256                                 }
257                         }
258                         else
259                         {
260                                 /*if(block->getLightingExpired()){
261                                         lighting_invalidated_blocks[block->getPos()] = block;
262                                 }*/
263                         }
264
265                         // TODO: Some additional checking and lighting updating,
266                         //       see emergeBlock
267                 }
268
269                 {//envlock
270                 JMutexAutoLock envlock(m_server->m_env_mutex);
271                 
272                 if(got_block)
273                 {
274                         /*
275                                 Collect a list of blocks that have been modified in
276                                 addition to the fetched one.
277                         */
278
279 #if 0
280                         if(lighting_invalidated_blocks.size() > 0)
281                         {
282                                 /*infostream<<"lighting "<<lighting_invalidated_blocks.size()
283                                                 <<" blocks"<<std::endl;*/
284                         
285                                 // 50-100ms for single block generation
286                                 //TimeTaker timer("** EmergeThread updateLighting");
287                                 
288                                 // Update lighting without locking the environment mutex,
289                                 // add modified blocks to changed blocks
290                                 map.updateLighting(lighting_invalidated_blocks, modified_blocks);
291                         }
292                                 
293                         // Add all from changed_blocks to modified_blocks
294                         for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
295                                         i.atEnd() == false; i++)
296                         {
297                                 MapBlock *block = i.getNode()->getValue();
298                                 modified_blocks.insert(block->getPos(), block);
299                         }
300 #endif
301                 }
302                 // If we got no block, there should be no invalidated blocks
303                 else
304                 {
305                         //assert(lighting_invalidated_blocks.size() == 0);
306                 }
307
308                 }//envlock
309
310                 /*
311                         Set sent status of modified blocks on clients
312                 */
313         
314                 // NOTE: Server's clients are also behind the connection mutex
315                 JMutexAutoLock lock(m_server->m_con_mutex);
316
317                 /*
318                         Add the originally fetched block to the modified list
319                 */
320                 if(got_block)
321                 {
322                         modified_blocks.insert(p, block);
323                 }
324                 
325                 /*
326                         Set the modified blocks unsent for all the clients
327                 */
328                 
329                 for(core::map<u16, RemoteClient*>::Iterator
330                                 i = m_server->m_clients.getIterator();
331                                 i.atEnd() == false; i++)
332                 {
333                         RemoteClient *client = i.getNode()->getValue();
334                         
335                         if(modified_blocks.size() > 0)
336                         {
337                                 // Remove block from sent history
338                                 client->SetBlocksNotSent(modified_blocks);
339                         }
340                 }
341                 
342         }
343
344         END_DEBUG_EXCEPTION_HANDLER(errorstream)
345
346         return NULL;
347 }
348
349 void RemoteClient::GetNextBlocks(Server *server, float dtime,
350                 core::array<PrioritySortedBlockTransfer> &dest)
351 {
352         DSTACK(__FUNCTION_NAME);
353         
354         /*u32 timer_result;
355         TimeTaker timer("RemoteClient::GetNextBlocks", &timer_result);*/
356         
357         // Increment timers
358         m_nothing_to_send_pause_timer -= dtime;
359         m_nearest_unsent_reset_timer += dtime;
360         
361         if(m_nothing_to_send_pause_timer >= 0)
362         {
363                 return;
364         }
365
366         // Won't send anything if already sending
367         if(m_blocks_sending.size() >= g_settings->getU16
368                         ("max_simultaneous_block_sends_per_client"))
369         {
370                 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
371                 return;
372         }
373
374         //TimeTaker timer("RemoteClient::GetNextBlocks");
375         
376         Player *player = server->m_env->getPlayer(peer_id);
377
378         assert(player != NULL);
379
380         v3f playerpos = player->getPosition();
381         v3f playerspeed = player->getSpeed();
382         v3f playerspeeddir(0,0,0);
383         if(playerspeed.getLength() > 1.0*BS)
384                 playerspeeddir = playerspeed / playerspeed.getLength();
385         // Predict to next block
386         v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS;
387
388         v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
389
390         v3s16 center = getNodeBlockPos(center_nodepos);
391         
392         // Camera position and direction
393         v3f camera_pos = player->getEyePosition();
394         v3f camera_dir = v3f(0,0,1);
395         camera_dir.rotateYZBy(player->getPitch());
396         camera_dir.rotateXZBy(player->getYaw());
397
398         /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
399                         <<camera_dir.Z<<")"<<std::endl;*/
400
401         /*
402                 Get the starting value of the block finder radius.
403         */
404                 
405         if(m_last_center != center)
406         {
407                 m_nearest_unsent_d = 0;
408                 m_last_center = center;
409         }
410
411         /*infostream<<"m_nearest_unsent_reset_timer="
412                         <<m_nearest_unsent_reset_timer<<std::endl;*/
413                         
414         // Reset periodically to workaround for some bugs or stuff
415         if(m_nearest_unsent_reset_timer > 20.0)
416         {
417                 m_nearest_unsent_reset_timer = 0;
418                 m_nearest_unsent_d = 0;
419                 //infostream<<"Resetting m_nearest_unsent_d for "
420                 //              <<server->getPlayerName(peer_id)<<std::endl;
421         }
422
423         //s16 last_nearest_unsent_d = m_nearest_unsent_d;
424         s16 d_start = m_nearest_unsent_d;
425
426         //infostream<<"d_start="<<d_start<<std::endl;
427
428         u16 max_simul_sends_setting = g_settings->getU16
429                         ("max_simultaneous_block_sends_per_client");
430         u16 max_simul_sends_usually = max_simul_sends_setting;
431
432         /*
433                 Check the time from last addNode/removeNode.
434                 
435                 Decrease send rate if player is building stuff.
436         */
437         m_time_from_building += dtime;
438         if(m_time_from_building < g_settings->getFloat(
439                                 "full_block_send_enable_min_time_from_building"))
440         {
441                 max_simul_sends_usually
442                         = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
443         }
444         
445         /*
446                 Number of blocks sending + number of blocks selected for sending
447         */
448         u32 num_blocks_selected = m_blocks_sending.size();
449         
450         /*
451                 next time d will be continued from the d from which the nearest
452                 unsent block was found this time.
453
454                 This is because not necessarily any of the blocks found this
455                 time are actually sent.
456         */
457         s32 new_nearest_unsent_d = -1;
458
459         s16 d_max = g_settings->getS16("max_block_send_distance");
460         s16 d_max_gen = g_settings->getS16("max_block_generate_distance");
461         
462         // Don't loop very much at a time
463         s16 max_d_increment_at_time = 2;
464         if(d_max > d_start + max_d_increment_at_time)
465                 d_max = d_start + max_d_increment_at_time;
466         /*if(d_max_gen > d_start+2)
467                 d_max_gen = d_start+2;*/
468         
469         //infostream<<"Starting from "<<d_start<<std::endl;
470
471         s32 nearest_emerged_d = -1;
472         s32 nearest_emergefull_d = -1;
473         s32 nearest_sent_d = -1;
474         bool queue_is_full = false;
475         
476         s16 d;
477         for(d = d_start; d <= d_max; d++)
478         {
479                 /*errorstream<<"checking d="<<d<<" for "
480                                 <<server->getPlayerName(peer_id)<<std::endl;*/
481                 //infostream<<"RemoteClient::SendBlocks(): d="<<d<<std::endl;
482                 
483                 /*
484                         If m_nearest_unsent_d was changed by the EmergeThread
485                         (it can change it to 0 through SetBlockNotSent),
486                         update our d to it.
487                         Else update m_nearest_unsent_d
488                 */
489                 /*if(m_nearest_unsent_d != last_nearest_unsent_d)
490                 {
491                         d = m_nearest_unsent_d;
492                         last_nearest_unsent_d = m_nearest_unsent_d;
493                 }*/
494
495                 /*
496                         Get the border/face dot coordinates of a "d-radiused"
497                         box
498                 */
499                 core::list<v3s16> list;
500                 getFacePositions(list, d);
501                 
502                 core::list<v3s16>::Iterator li;
503                 for(li=list.begin(); li!=list.end(); li++)
504                 {
505                         v3s16 p = *li + center;
506                         
507                         /*
508                                 Send throttling
509                                 - Don't allow too many simultaneous transfers
510                                 - EXCEPT when the blocks are very close
511
512                                 Also, don't send blocks that are already flying.
513                         */
514                         
515                         // Start with the usual maximum
516                         u16 max_simul_dynamic = max_simul_sends_usually;
517                         
518                         // If block is very close, allow full maximum
519                         if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
520                                 max_simul_dynamic = max_simul_sends_setting;
521
522                         // Don't select too many blocks for sending
523                         if(num_blocks_selected >= max_simul_dynamic)
524                         {
525                                 queue_is_full = true;
526                                 goto queue_full_break;
527                         }
528                         
529                         // Don't send blocks that are currently being transferred
530                         if(m_blocks_sending.find(p) != NULL)
531                                 continue;
532                 
533                         /*
534                                 Do not go over-limit
535                         */
536                         if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
537                         || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
538                         || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
539                         || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
540                         || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
541                         || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
542                                 continue;
543                 
544                         // If this is true, inexistent block will be made from scratch
545                         bool generate = d <= d_max_gen;
546                         
547                         {
548                                 /*// Limit the generating area vertically to 2/3
549                                 if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
550                                         generate = false;*/
551
552                                 // Limit the send area vertically to 1/2
553                                 if(abs(p.Y - center.Y) > d_max / 2)
554                                         continue;
555                         }
556
557 #if 0
558                         /*
559                                 If block is far away, don't generate it unless it is
560                                 near ground level.
561                         */
562                         if(d >= 4)
563                         {
564         #if 1
565                                 // Block center y in nodes
566                                 f32 y = (f32)(p.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE/2);
567                                 // Don't generate if it's very high or very low
568                                 if(y < -64 || y > 64)
569                                         generate = false;
570         #endif
571         #if 0
572                                 v2s16 p2d_nodes_center(
573                                         MAP_BLOCKSIZE*p.X,
574                                         MAP_BLOCKSIZE*p.Z);
575                                 
576                                 // Get ground height in nodes
577                                 s16 gh = server->m_env->getServerMap().findGroundLevel(
578                                                 p2d_nodes_center);
579
580                                 // If differs a lot, don't generate
581                                 if(fabs(gh - y) > MAP_BLOCKSIZE*2)
582                                         generate = false;
583                                         // Actually, don't even send it
584                                         //continue;
585         #endif
586                         }
587 #endif
588
589                         //infostream<<"d="<<d<<std::endl;
590 #if 1
591                         /*
592                                 Don't generate or send if not in sight
593                                 FIXME This only works if the client uses a small enough
594                                 FOV setting. The default of 72 degrees is fine.
595                         */
596
597                         float camera_fov = (72.0*PI/180) * 4./3.;
598                         if(isBlockInSight(p, camera_pos, camera_dir, camera_fov, 10000*BS) == false)
599                         {
600                                 continue;
601                         }
602 #endif
603                         /*
604                                 Don't send already sent blocks
605                         */
606                         {
607                                 if(m_blocks_sent.find(p) != NULL)
608                                 {
609                                         continue;
610                                 }
611                         }
612
613                         /*
614                                 Check if map has this block
615                         */
616                         MapBlock *block = server->m_env->getMap().getBlockNoCreateNoEx(p);
617                         
618                         bool surely_not_found_on_disk = false;
619                         bool block_is_invalid = false;
620                         if(block != NULL)
621                         {
622                                 // Reset usage timer, this block will be of use in the future.
623                                 block->resetUsageTimer();
624
625                                 // Block is dummy if data doesn't exist.
626                                 // It means it has been not found from disk and not generated
627                                 if(block->isDummy())
628                                 {
629                                         surely_not_found_on_disk = true;
630                                 }
631                                 
632                                 // Block is valid if lighting is up-to-date and data exists
633                                 if(block->isValid() == false)
634                                 {
635                                         block_is_invalid = true;
636                                 }
637                                 
638                                 /*if(block->isFullyGenerated() == false)
639                                 {
640                                         block_is_invalid = true;
641                                 }*/
642
643 #if 0
644                                 v2s16 p2d(p.X, p.Z);
645                                 ServerMap *map = (ServerMap*)(&server->m_env->getMap());
646                                 v2s16 chunkpos = map->sector_to_chunk(p2d);
647                                 if(map->chunkNonVolatile(chunkpos) == false)
648                                         block_is_invalid = true;
649 #endif
650                                 if(block->isGenerated() == false)
651                                         block_is_invalid = true;
652 #if 1
653                                 /*
654                                         If block is not close, don't send it unless it is near
655                                         ground level.
656
657                                         Block is near ground level if night-time mesh
658                                         differs from day-time mesh.
659                                 */
660                                 if(d >= 4)
661                                 {
662                                         if(block->dayNightDiffed() == false)
663                                                 continue;
664                                 }
665 #endif
666                         }
667
668                         /*
669                                 If block has been marked to not exist on disk (dummy)
670                                 and generating new ones is not wanted, skip block.
671                         */
672                         if(generate == false && surely_not_found_on_disk == true)
673                         {
674                                 // get next one.
675                                 continue;
676                         }
677
678                         /*
679                                 Add inexistent block to emerge queue.
680                         */
681                         if(block == NULL || surely_not_found_on_disk || block_is_invalid)
682                         {
683                                 //TODO: Get value from somewhere
684                                 // Allow only one block in emerge queue
685                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
686                                 // Allow two blocks in queue per client
687                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
688                                 if(server->m_emerge_queue.peerItemCount(peer_id) < 25)
689                                 {
690                                         //infostream<<"Adding block to emerge queue"<<std::endl;
691                                         
692                                         // Add it to the emerge queue and trigger the thread
693                                         
694                                         u8 flags = 0;
695                                         if(generate == false)
696                                                 flags |= BLOCK_EMERGE_FLAG_FROMDISK;
697                                         
698                                         server->m_emerge_queue.addBlock(peer_id, p, flags);
699                                         server->m_emergethread.trigger();
700
701                                         if(nearest_emerged_d == -1)
702                                                 nearest_emerged_d = d;
703                                 } else {
704                                         if(nearest_emergefull_d == -1)
705                                                 nearest_emergefull_d = d;
706                                 }
707                                 
708                                 // get next one.
709                                 continue;
710                         }
711
712                         if(nearest_sent_d == -1)
713                                 nearest_sent_d = d;
714
715                         /*
716                                 Add block to send queue
717                         */
718
719                         /*errorstream<<"sending from d="<<d<<" to "
720                                         <<server->getPlayerName(peer_id)<<std::endl;*/
721
722                         PrioritySortedBlockTransfer q((float)d, p, peer_id);
723
724                         dest.push_back(q);
725
726                         num_blocks_selected += 1;
727                 }
728         }
729 queue_full_break:
730
731         //infostream<<"Stopped at "<<d<<std::endl;
732         
733         // If nothing was found for sending and nothing was queued for
734         // emerging, continue next time browsing from here
735         if(nearest_emerged_d != -1){
736                 new_nearest_unsent_d = nearest_emerged_d;
737         } else if(nearest_emergefull_d != -1){
738                 new_nearest_unsent_d = nearest_emergefull_d;
739         } else {
740                 if(d > g_settings->getS16("max_block_send_distance")){
741                         new_nearest_unsent_d = 0;
742                         m_nothing_to_send_pause_timer = 2.0;
743                         /*infostream<<"GetNextBlocks(): d wrapped around for "
744                                         <<server->getPlayerName(peer_id)
745                                         <<"; setting to 0 and pausing"<<std::endl;*/
746                 } else {
747                         if(nearest_sent_d != -1)
748                                 new_nearest_unsent_d = nearest_sent_d;
749                         else
750                                 new_nearest_unsent_d = d;
751                 }
752         }
753
754         if(new_nearest_unsent_d != -1)
755                 m_nearest_unsent_d = new_nearest_unsent_d;
756
757         /*timer_result = timer.stop(true);
758         if(timer_result != 0)
759                 infostream<<"GetNextBlocks duration: "<<timer_result<<" (!=0)"<<std::endl;*/
760 }
761
762 void RemoteClient::SendObjectData(
763                 Server *server,
764                 float dtime,
765                 core::map<v3s16, bool> &stepped_blocks
766         )
767 {
768         DSTACK(__FUNCTION_NAME);
769
770         // Can't send anything without knowing version
771         if(serialization_version == SER_FMT_VER_INVALID)
772         {
773                 infostream<<"RemoteClient::SendObjectData(): Not sending, no version."
774                                 <<std::endl;
775                 return;
776         }
777
778         /*
779                 Send a TOCLIENT_OBJECTDATA packet.
780                 Sent as unreliable.
781
782                 u16 command
783                 u16 number of player positions
784                 for each player:
785                         u16 peer_id
786                         v3s32 position*100
787                         v3s32 speed*100
788                         s32 pitch*100
789                         s32 yaw*100
790                 u16 count of blocks
791                 for each block:
792                         block objects
793         */
794
795         std::ostringstream os(std::ios_base::binary);
796         u8 buf[12];
797         
798         // Write command
799         writeU16(buf, TOCLIENT_OBJECTDATA);
800         os.write((char*)buf, 2);
801         
802         /*
803                 Get and write player data
804         */
805         
806         // Get connected players
807         core::list<Player*> players = server->m_env->getPlayers(true);
808
809         // Write player count
810         u16 playercount = players.size();
811         writeU16(buf, playercount);
812         os.write((char*)buf, 2);
813
814         core::list<Player*>::Iterator i;
815         for(i = players.begin();
816                         i != players.end(); i++)
817         {
818                 Player *player = *i;
819
820                 v3f pf = player->getPosition();
821                 v3f sf = player->getSpeed();
822
823                 v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100);
824                 v3s32 speed_i   (sf.X*100, sf.Y*100, sf.Z*100);
825                 s32   pitch_i   (player->getPitch() * 100);
826                 s32   yaw_i     (player->getYaw() * 100);
827                 
828                 writeU16(buf, player->peer_id);
829                 os.write((char*)buf, 2);
830                 writeV3S32(buf, position_i);
831                 os.write((char*)buf, 12);
832                 writeV3S32(buf, speed_i);
833                 os.write((char*)buf, 12);
834                 writeS32(buf, pitch_i);
835                 os.write((char*)buf, 4);
836                 writeS32(buf, yaw_i);
837                 os.write((char*)buf, 4);
838         }
839         
840         /*
841                 Get and write object data (dummy, for compatibility)
842         */
843
844         // Write block count
845         writeU16(buf, 0);
846         os.write((char*)buf, 2);
847
848         /*
849                 Send data
850         */
851         
852         //infostream<<"Server: Sending object data to "<<peer_id<<std::endl;
853
854         // Make data buffer
855         std::string s = os.str();
856         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
857         // Send as unreliable
858         server->m_con.Send(peer_id, 0, data, false);
859 }
860
861 void RemoteClient::GotBlock(v3s16 p)
862 {
863         if(m_blocks_sending.find(p) != NULL)
864                 m_blocks_sending.remove(p);
865         else
866         {
867                 /*infostream<<"RemoteClient::GotBlock(): Didn't find in"
868                                 " m_blocks_sending"<<std::endl;*/
869                 m_excess_gotblocks++;
870         }
871         m_blocks_sent.insert(p, true);
872 }
873
874 void RemoteClient::SentBlock(v3s16 p)
875 {
876         if(m_blocks_sending.find(p) == NULL)
877                 m_blocks_sending.insert(p, 0.0);
878         else
879                 infostream<<"RemoteClient::SentBlock(): Sent block"
880                                 " already in m_blocks_sending"<<std::endl;
881 }
882
883 void RemoteClient::SetBlockNotSent(v3s16 p)
884 {
885         m_nearest_unsent_d = 0;
886         
887         if(m_blocks_sending.find(p) != NULL)
888                 m_blocks_sending.remove(p);
889         if(m_blocks_sent.find(p) != NULL)
890                 m_blocks_sent.remove(p);
891 }
892
893 void RemoteClient::SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks)
894 {
895         m_nearest_unsent_d = 0;
896         
897         for(core::map<v3s16, MapBlock*>::Iterator
898                         i = blocks.getIterator();
899                         i.atEnd()==false; i++)
900         {
901                 v3s16 p = i.getNode()->getKey();
902
903                 if(m_blocks_sending.find(p) != NULL)
904                         m_blocks_sending.remove(p);
905                 if(m_blocks_sent.find(p) != NULL)
906                         m_blocks_sent.remove(p);
907         }
908 }
909
910 /*
911         PlayerInfo
912 */
913
914 PlayerInfo::PlayerInfo()
915 {
916         name[0] = 0;
917         avg_rtt = 0;
918 }
919
920 void PlayerInfo::PrintLine(std::ostream *s)
921 {
922         (*s)<<id<<": ";
923         (*s)<<"\""<<name<<"\" ("
924                         <<(position.X/10)<<","<<(position.Y/10)
925                         <<","<<(position.Z/10)<<") ";
926         address.print(s);
927         (*s)<<" avg_rtt="<<avg_rtt;
928         (*s)<<std::endl;
929 }
930
931 u32 PIChecksum(core::list<PlayerInfo> &l)
932 {
933         core::list<PlayerInfo>::Iterator i;
934         u32 checksum = 1;
935         u32 a = 10;
936         for(i=l.begin(); i!=l.end(); i++)
937         {
938                 checksum += a * (i->id+1);
939                 checksum ^= 0x435aafcd;
940                 a *= 10;
941         }
942         return checksum;
943 }
944
945 /*
946         Server
947 */
948
949 Server::Server(
950                 std::string mapsavedir,
951                 std::string configpath
952         ):
953         m_env(NULL),
954         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
955         m_authmanager(mapsavedir+DIR_DELIM+"auth.txt"),
956         m_banmanager(mapsavedir+DIR_DELIM+"ipban.txt"),
957         m_lua(NULL),
958         //m_scriptapi(NULL),
959         m_thread(this),
960         m_emergethread(this),
961         m_time_counter(0),
962         m_time_of_day_send_timer(0),
963         m_uptime(0),
964         m_mapsavedir(mapsavedir),
965         m_configpath(configpath),
966         m_shutdown_requested(false),
967         m_ignore_map_edit_events(false),
968         m_ignore_map_edit_events_peer_id(0)
969 {
970         m_liquid_transform_timer = 0.0;
971         m_print_info_timer = 0.0;
972         m_objectdata_timer = 0.0;
973         m_emergethread_trigger_timer = 0.0;
974         m_savemap_timer = 0.0;
975         
976         m_env_mutex.Init();
977         m_con_mutex.Init();
978         m_step_dtime_mutex.Init();
979         m_step_dtime = 0.0;
980
981         JMutexAutoLock envlock(m_env_mutex);
982         JMutexAutoLock conlock(m_con_mutex);
983         
984         // Initialize scripting
985         
986         infostream<<"Server: Initializing scripting"<<std::endl;
987         m_lua = script_init();
988         assert(m_lua);
989         // Export API
990         scriptapi_export(m_lua, this);
991         // Load and run scripts
992         std::string defaultscript = porting::path_data + DIR_DELIM
993                         + "scripts" + DIR_DELIM + "default.lua";
994         bool success = script_load(m_lua, defaultscript.c_str());
995         if(!success){
996                 errorstream<<"Server: Failed to load and run "
997                                 <<defaultscript<<std::endl;
998                 assert(0);
999         }
1000         
1001         // Initialize Environment
1002         
1003         m_env = new ServerEnvironment(new ServerMap(mapsavedir), m_lua);
1004         
1005         // Register us to receive map edit events
1006         m_env->getMap().addEventReceiver(this);
1007
1008         // If file exists, load environment metadata
1009         if(fs::PathExists(m_mapsavedir+DIR_DELIM+"env_meta.txt"))
1010         {
1011                 infostream<<"Server: Loading environment metadata"<<std::endl;
1012                 m_env->loadMeta(m_mapsavedir);
1013         }
1014
1015         // Load players
1016         infostream<<"Server: Loading players"<<std::endl;
1017         m_env->deSerializePlayers(m_mapsavedir);
1018 }
1019
1020 Server::~Server()
1021 {
1022         infostream<<"Server::~Server()"<<std::endl;
1023
1024         /*
1025                 Send shutdown message
1026         */
1027         {
1028                 JMutexAutoLock conlock(m_con_mutex);
1029                 
1030                 std::wstring line = L"*** Server shutting down";
1031
1032                 /*
1033                         Send the message to clients
1034                 */
1035                 for(core::map<u16, RemoteClient*>::Iterator
1036                         i = m_clients.getIterator();
1037                         i.atEnd() == false; i++)
1038                 {
1039                         // Get client and check that it is valid
1040                         RemoteClient *client = i.getNode()->getValue();
1041                         assert(client->peer_id == i.getNode()->getKey());
1042                         if(client->serialization_version == SER_FMT_VER_INVALID)
1043                                 continue;
1044
1045                         try{
1046                                 SendChatMessage(client->peer_id, line);
1047                         }
1048                         catch(con::PeerNotFoundException &e)
1049                         {}
1050                 }
1051         }
1052         
1053         {
1054                 JMutexAutoLock envlock(m_env_mutex);
1055
1056                 /*
1057                         Save players
1058                 */
1059                 infostream<<"Server: Saving players"<<std::endl;
1060                 m_env->serializePlayers(m_mapsavedir);
1061
1062                 /*
1063                         Save environment metadata
1064                 */
1065                 infostream<<"Server: Saving environment metadata"<<std::endl;
1066                 m_env->saveMeta(m_mapsavedir);
1067         }
1068                 
1069         /*
1070                 Stop threads
1071         */
1072         stop();
1073         
1074         /*
1075                 Delete clients
1076         */
1077         {
1078                 JMutexAutoLock clientslock(m_con_mutex);
1079
1080                 for(core::map<u16, RemoteClient*>::Iterator
1081                         i = m_clients.getIterator();
1082                         i.atEnd() == false; i++)
1083                 {
1084                         /*// Delete player
1085                         // NOTE: These are removed by env destructor
1086                         {
1087                                 u16 peer_id = i.getNode()->getKey();
1088                                 JMutexAutoLock envlock(m_env_mutex);
1089                                 m_env->removePlayer(peer_id);
1090                         }*/
1091                         
1092                         // Delete client
1093                         delete i.getNode()->getValue();
1094                 }
1095         }
1096
1097         // Delete Environment
1098         delete m_env;
1099         
1100         // Deinitialize scripting
1101         infostream<<"Server: Deinitializing scripting"<<std::endl;
1102         script_deinit(m_lua);
1103 }
1104
1105 void Server::start(unsigned short port)
1106 {
1107         DSTACK(__FUNCTION_NAME);
1108         // Stop thread if already running
1109         m_thread.stop();
1110         
1111         // Initialize connection
1112         m_con.SetTimeoutMs(30);
1113         m_con.Serve(port);
1114
1115         // Start thread
1116         m_thread.setRun(true);
1117         m_thread.Start();
1118         
1119         infostream<<"Server: Started on port "<<port<<std::endl;
1120 }
1121
1122 void Server::stop()
1123 {
1124         DSTACK(__FUNCTION_NAME);
1125         
1126         infostream<<"Server: Stopping and waiting threads"<<std::endl;
1127
1128         // Stop threads (set run=false first so both start stopping)
1129         m_thread.setRun(false);
1130         m_emergethread.setRun(false);
1131         m_thread.stop();
1132         m_emergethread.stop();
1133         
1134         infostream<<"Server: Threads stopped"<<std::endl;
1135 }
1136
1137 void Server::step(float dtime)
1138 {
1139         DSTACK(__FUNCTION_NAME);
1140         // Limit a bit
1141         if(dtime > 2.0)
1142                 dtime = 2.0;
1143         {
1144                 JMutexAutoLock lock(m_step_dtime_mutex);
1145                 m_step_dtime += dtime;
1146         }
1147 }
1148
1149 void Server::AsyncRunStep()
1150 {
1151         DSTACK(__FUNCTION_NAME);
1152         
1153         g_profiler->add("Server::AsyncRunStep (num)", 1);
1154         
1155         float dtime;
1156         {
1157                 JMutexAutoLock lock1(m_step_dtime_mutex);
1158                 dtime = m_step_dtime;
1159         }
1160         
1161         {
1162                 ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
1163                 // Send blocks to clients
1164                 SendBlocks(dtime);
1165         }
1166         
1167         if(dtime < 0.001)
1168                 return;
1169         
1170         g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
1171
1172         //infostream<<"Server steps "<<dtime<<std::endl;
1173         //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
1174         
1175         {
1176                 JMutexAutoLock lock1(m_step_dtime_mutex);
1177                 m_step_dtime -= dtime;
1178         }
1179
1180         /*
1181                 Update uptime
1182         */
1183         {
1184                 m_uptime.set(m_uptime.get() + dtime);
1185         }
1186         
1187         {
1188                 // Process connection's timeouts
1189                 JMutexAutoLock lock2(m_con_mutex);
1190                 ScopeProfiler sp(g_profiler, "Server: connection timeout processing");
1191                 m_con.RunTimeouts(dtime);
1192         }
1193         
1194         {
1195                 // This has to be called so that the client list gets synced
1196                 // with the peer list of the connection
1197                 handlePeerChanges();
1198         }
1199
1200         /*
1201                 Update m_time_of_day and overall game time
1202         */
1203         {
1204                 JMutexAutoLock envlock(m_env_mutex);
1205
1206                 m_time_counter += dtime;
1207                 f32 speed = g_settings->getFloat("time_speed") * 24000./(24.*3600);
1208                 u32 units = (u32)(m_time_counter*speed);
1209                 m_time_counter -= (f32)units / speed;
1210                 
1211                 m_env->setTimeOfDay((m_env->getTimeOfDay() + units) % 24000);
1212                 
1213                 //infostream<<"Server: m_time_of_day = "<<m_time_of_day.get()<<std::endl;
1214
1215                 /*
1216                         Send to clients at constant intervals
1217                 */
1218
1219                 m_time_of_day_send_timer -= dtime;
1220                 if(m_time_of_day_send_timer < 0.0)
1221                 {
1222                         m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
1223
1224                         //JMutexAutoLock envlock(m_env_mutex);
1225                         JMutexAutoLock conlock(m_con_mutex);
1226
1227                         for(core::map<u16, RemoteClient*>::Iterator
1228                                 i = m_clients.getIterator();
1229                                 i.atEnd() == false; i++)
1230                         {
1231                                 RemoteClient *client = i.getNode()->getValue();
1232                                 //Player *player = m_env->getPlayer(client->peer_id);
1233                                 
1234                                 SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
1235                                                 m_env->getTimeOfDay());
1236                                 // Send as reliable
1237                                 m_con.Send(client->peer_id, 0, data, true);
1238                         }
1239                 }
1240         }
1241
1242         {
1243                 JMutexAutoLock lock(m_env_mutex);
1244                 // Step environment
1245                 ScopeProfiler sp(g_profiler, "SEnv step");
1246                 ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
1247                 m_env->step(dtime);
1248         }
1249                 
1250         const float map_timer_and_unload_dtime = 5.15;
1251         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
1252         {
1253                 JMutexAutoLock lock(m_env_mutex);
1254                 // Run Map's timers and unload unused data
1255                 ScopeProfiler sp(g_profiler, "Server: map timer and unload");
1256                 m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
1257                                 g_settings->getFloat("server_unload_unused_data_timeout"));
1258         }
1259         
1260         /*
1261                 Do background stuff
1262         */
1263         
1264         /*
1265                 Transform liquids
1266         */
1267         m_liquid_transform_timer += dtime;
1268         if(m_liquid_transform_timer >= 1.00)
1269         {
1270                 m_liquid_transform_timer -= 1.00;
1271                 
1272                 JMutexAutoLock lock(m_env_mutex);
1273
1274                 ScopeProfiler sp(g_profiler, "Server: liquid transform");
1275
1276                 core::map<v3s16, MapBlock*> modified_blocks;
1277                 m_env->getMap().transformLiquids(modified_blocks);
1278 #if 0           
1279                 /*
1280                         Update lighting
1281                 */
1282                 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1283                 ServerMap &map = ((ServerMap&)m_env->getMap());
1284                 map.updateLighting(modified_blocks, lighting_modified_blocks);
1285                 
1286                 // Add blocks modified by lighting to modified_blocks
1287                 for(core::map<v3s16, MapBlock*>::Iterator
1288                                 i = lighting_modified_blocks.getIterator();
1289                                 i.atEnd() == false; i++)
1290                 {
1291                         MapBlock *block = i.getNode()->getValue();
1292                         modified_blocks.insert(block->getPos(), block);
1293                 }
1294 #endif
1295                 /*
1296                         Set the modified blocks unsent for all the clients
1297                 */
1298                 
1299                 JMutexAutoLock lock2(m_con_mutex);
1300
1301                 for(core::map<u16, RemoteClient*>::Iterator
1302                                 i = m_clients.getIterator();
1303                                 i.atEnd() == false; i++)
1304                 {
1305                         RemoteClient *client = i.getNode()->getValue();
1306                         
1307                         if(modified_blocks.size() > 0)
1308                         {
1309                                 // Remove block from sent history
1310                                 client->SetBlocksNotSent(modified_blocks);
1311                         }
1312                 }
1313         }
1314
1315         // Periodically print some info
1316         {
1317                 float &counter = m_print_info_timer;
1318                 counter += dtime;
1319                 if(counter >= 30.0)
1320                 {
1321                         counter = 0.0;
1322
1323                         JMutexAutoLock lock2(m_con_mutex);
1324                         
1325                         if(m_clients.size() != 0)
1326                                 infostream<<"Players:"<<std::endl;
1327                         for(core::map<u16, RemoteClient*>::Iterator
1328                                 i = m_clients.getIterator();
1329                                 i.atEnd() == false; i++)
1330                         {
1331                                 //u16 peer_id = i.getNode()->getKey();
1332                                 RemoteClient *client = i.getNode()->getValue();
1333                                 Player *player = m_env->getPlayer(client->peer_id);
1334                                 if(player==NULL)
1335                                         continue;
1336                                 infostream<<"* "<<player->getName()<<"\t";
1337                                 client->PrintInfo(infostream);
1338                         }
1339                 }
1340         }
1341
1342         //if(g_settings->getBool("enable_experimental"))
1343         {
1344
1345         /*
1346                 Check added and deleted active objects
1347         */
1348         {
1349                 //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
1350                 JMutexAutoLock envlock(m_env_mutex);
1351                 JMutexAutoLock conlock(m_con_mutex);
1352
1353                 ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
1354
1355                 // Radius inside which objects are active
1356                 s16 radius = g_settings->getS16("active_object_send_range_blocks");
1357                 radius *= MAP_BLOCKSIZE;
1358
1359                 for(core::map<u16, RemoteClient*>::Iterator
1360                         i = m_clients.getIterator();
1361                         i.atEnd() == false; i++)
1362                 {
1363                         RemoteClient *client = i.getNode()->getValue();
1364                         Player *player = m_env->getPlayer(client->peer_id);
1365                         if(player==NULL)
1366                         {
1367                                 // This can happen if the client timeouts somehow
1368                                 /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
1369                                                 <<client->peer_id
1370                                                 <<" has no associated player"<<std::endl;*/
1371                                 continue;
1372                         }
1373                         v3s16 pos = floatToInt(player->getPosition(), BS);
1374
1375                         core::map<u16, bool> removed_objects;
1376                         core::map<u16, bool> added_objects;
1377                         m_env->getRemovedActiveObjects(pos, radius,
1378                                         client->m_known_objects, removed_objects);
1379                         m_env->getAddedActiveObjects(pos, radius,
1380                                         client->m_known_objects, added_objects);
1381                         
1382                         // Ignore if nothing happened
1383                         if(removed_objects.size() == 0 && added_objects.size() == 0)
1384                         {
1385                                 //infostream<<"active objects: none changed"<<std::endl;
1386                                 continue;
1387                         }
1388                         
1389                         std::string data_buffer;
1390
1391                         char buf[4];
1392                         
1393                         // Handle removed objects
1394                         writeU16((u8*)buf, removed_objects.size());
1395                         data_buffer.append(buf, 2);
1396                         for(core::map<u16, bool>::Iterator
1397                                         i = removed_objects.getIterator();
1398                                         i.atEnd()==false; i++)
1399                         {
1400                                 // Get object
1401                                 u16 id = i.getNode()->getKey();
1402                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1403
1404                                 // Add to data buffer for sending
1405                                 writeU16((u8*)buf, i.getNode()->getKey());
1406                                 data_buffer.append(buf, 2);
1407                                 
1408                                 // Remove from known objects
1409                                 client->m_known_objects.remove(i.getNode()->getKey());
1410
1411                                 if(obj && obj->m_known_by_count > 0)
1412                                         obj->m_known_by_count--;
1413                         }
1414
1415                         // Handle added objects
1416                         writeU16((u8*)buf, added_objects.size());
1417                         data_buffer.append(buf, 2);
1418                         for(core::map<u16, bool>::Iterator
1419                                         i = added_objects.getIterator();
1420                                         i.atEnd()==false; i++)
1421                         {
1422                                 // Get object
1423                                 u16 id = i.getNode()->getKey();
1424                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1425                                 
1426                                 // Get object type
1427                                 u8 type = ACTIVEOBJECT_TYPE_INVALID;
1428                                 if(obj == NULL)
1429                                         infostream<<"WARNING: "<<__FUNCTION_NAME
1430                                                         <<": NULL object"<<std::endl;
1431                                 else
1432                                         type = obj->getType();
1433
1434                                 // Add to data buffer for sending
1435                                 writeU16((u8*)buf, id);
1436                                 data_buffer.append(buf, 2);
1437                                 writeU8((u8*)buf, type);
1438                                 data_buffer.append(buf, 1);
1439                                 
1440                                 if(obj)
1441                                         data_buffer.append(serializeLongString(
1442                                                         obj->getClientInitializationData()));
1443                                 else
1444                                         data_buffer.append(serializeLongString(""));
1445
1446                                 // Add to known objects
1447                                 client->m_known_objects.insert(i.getNode()->getKey(), false);
1448
1449                                 if(obj)
1450                                         obj->m_known_by_count++;
1451                         }
1452
1453                         // Send packet
1454                         SharedBuffer<u8> reply(2 + data_buffer.size());
1455                         writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD);
1456                         memcpy((char*)&reply[2], data_buffer.c_str(),
1457                                         data_buffer.size());
1458                         // Send as reliable
1459                         m_con.Send(client->peer_id, 0, reply, true);
1460
1461                         infostream<<"Server: Sent object remove/add: "
1462                                         <<removed_objects.size()<<" removed, "
1463                                         <<added_objects.size()<<" added, "
1464                                         <<"packet size is "<<reply.getSize()<<std::endl;
1465                 }
1466
1467 #if 0
1468                 /*
1469                         Collect a list of all the objects known by the clients
1470                         and report it back to the environment.
1471                 */
1472
1473                 core::map<u16, bool> all_known_objects;
1474
1475                 for(core::map<u16, RemoteClient*>::Iterator
1476                         i = m_clients.getIterator();
1477                         i.atEnd() == false; i++)
1478                 {
1479                         RemoteClient *client = i.getNode()->getValue();
1480                         // Go through all known objects of client
1481                         for(core::map<u16, bool>::Iterator
1482                                         i = client->m_known_objects.getIterator();
1483                                         i.atEnd()==false; i++)
1484                         {
1485                                 u16 id = i.getNode()->getKey();
1486                                 all_known_objects[id] = true;
1487                         }
1488                 }
1489                 
1490                 m_env->setKnownActiveObjects(whatever);
1491 #endif
1492
1493         }
1494
1495         /*
1496                 Send object messages
1497         */
1498         {
1499                 JMutexAutoLock envlock(m_env_mutex);
1500                 JMutexAutoLock conlock(m_con_mutex);
1501
1502                 //ScopeProfiler sp(g_profiler, "Server: sending object messages");
1503
1504                 // Key = object id
1505                 // Value = data sent by object
1506                 core::map<u16, core::list<ActiveObjectMessage>* > buffered_messages;
1507
1508                 // Get active object messages from environment
1509                 for(;;)
1510                 {
1511                         ActiveObjectMessage aom = m_env->getActiveObjectMessage();
1512                         if(aom.id == 0)
1513                                 break;
1514                         
1515                         core::list<ActiveObjectMessage>* message_list = NULL;
1516                         core::map<u16, core::list<ActiveObjectMessage>* >::Node *n;
1517                         n = buffered_messages.find(aom.id);
1518                         if(n == NULL)
1519                         {
1520                                 message_list = new core::list<ActiveObjectMessage>;
1521                                 buffered_messages.insert(aom.id, message_list);
1522                         }
1523                         else
1524                         {
1525                                 message_list = n->getValue();
1526                         }
1527                         message_list->push_back(aom);
1528                 }
1529                 
1530                 // Route data to every client
1531                 for(core::map<u16, RemoteClient*>::Iterator
1532                         i = m_clients.getIterator();
1533                         i.atEnd()==false; i++)
1534                 {
1535                         RemoteClient *client = i.getNode()->getValue();
1536                         std::string reliable_data;
1537                         std::string unreliable_data;
1538                         // Go through all objects in message buffer
1539                         for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1540                                         j = buffered_messages.getIterator();
1541                                         j.atEnd()==false; j++)
1542                         {
1543                                 // If object is not known by client, skip it
1544                                 u16 id = j.getNode()->getKey();
1545                                 if(client->m_known_objects.find(id) == NULL)
1546                                         continue;
1547                                 // Get message list of object
1548                                 core::list<ActiveObjectMessage>* list = j.getNode()->getValue();
1549                                 // Go through every message
1550                                 for(core::list<ActiveObjectMessage>::Iterator
1551                                                 k = list->begin(); k != list->end(); k++)
1552                                 {
1553                                         // Compose the full new data with header
1554                                         ActiveObjectMessage aom = *k;
1555                                         std::string new_data;
1556                                         // Add object id
1557                                         char buf[2];
1558                                         writeU16((u8*)&buf[0], aom.id);
1559                                         new_data.append(buf, 2);
1560                                         // Add data
1561                                         new_data += serializeString(aom.datastring);
1562                                         // Add data to buffer
1563                                         if(aom.reliable)
1564                                                 reliable_data += new_data;
1565                                         else
1566                                                 unreliable_data += new_data;
1567                                 }
1568                         }
1569                         /*
1570                                 reliable_data and unreliable_data are now ready.
1571                                 Send them.
1572                         */
1573                         if(reliable_data.size() > 0)
1574                         {
1575                                 SharedBuffer<u8> reply(2 + reliable_data.size());
1576                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1577                                 memcpy((char*)&reply[2], reliable_data.c_str(),
1578                                                 reliable_data.size());
1579                                 // Send as reliable
1580                                 m_con.Send(client->peer_id, 0, reply, true);
1581                         }
1582                         if(unreliable_data.size() > 0)
1583                         {
1584                                 SharedBuffer<u8> reply(2 + unreliable_data.size());
1585                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1586                                 memcpy((char*)&reply[2], unreliable_data.c_str(),
1587                                                 unreliable_data.size());
1588                                 // Send as unreliable
1589                                 m_con.Send(client->peer_id, 0, reply, false);
1590                         }
1591
1592                         /*if(reliable_data.size() > 0 || unreliable_data.size() > 0)
1593                         {
1594                                 infostream<<"Server: Size of object message data: "
1595                                                 <<"reliable: "<<reliable_data.size()
1596                                                 <<", unreliable: "<<unreliable_data.size()
1597                                                 <<std::endl;
1598                         }*/
1599                 }
1600
1601                 // Clear buffered_messages
1602                 for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1603                                 i = buffered_messages.getIterator();
1604                                 i.atEnd()==false; i++)
1605                 {
1606                         delete i.getNode()->getValue();
1607                 }
1608         }
1609
1610         } // enable_experimental
1611
1612         /*
1613                 Send queued-for-sending map edit events.
1614         */
1615         {
1616                 // Don't send too many at a time
1617                 //u32 count = 0;
1618
1619                 // Single change sending is disabled if queue size is not small
1620                 bool disable_single_change_sending = false;
1621                 if(m_unsent_map_edit_queue.size() >= 4)
1622                         disable_single_change_sending = true;
1623
1624                 bool got_any_events = false;
1625
1626                 // We'll log the amount of each
1627                 Profiler prof;
1628
1629                 while(m_unsent_map_edit_queue.size() != 0)
1630                 {
1631                         got_any_events = true;
1632
1633                         MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
1634                         
1635                         // Players far away from the change are stored here.
1636                         // Instead of sending the changes, MapBlocks are set not sent
1637                         // for them.
1638                         core::list<u16> far_players;
1639
1640                         if(event->type == MEET_ADDNODE)
1641                         {
1642                                 //infostream<<"Server: MEET_ADDNODE"<<std::endl;
1643                                 prof.add("MEET_ADDNODE", 1);
1644                                 if(disable_single_change_sending)
1645                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1646                                                         &far_players, 5);
1647                                 else
1648                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1649                                                         &far_players, 30);
1650                         }
1651                         else if(event->type == MEET_REMOVENODE)
1652                         {
1653                                 //infostream<<"Server: MEET_REMOVENODE"<<std::endl;
1654                                 prof.add("MEET_REMOVENODE", 1);
1655                                 if(disable_single_change_sending)
1656                                         sendRemoveNode(event->p, event->already_known_by_peer,
1657                                                         &far_players, 5);
1658                                 else
1659                                         sendRemoveNode(event->p, event->already_known_by_peer,
1660                                                         &far_players, 30);
1661                         }
1662                         else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED)
1663                         {
1664                                 infostream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<<std::endl;
1665                                 prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
1666                                 setBlockNotSent(event->p);
1667                         }
1668                         else if(event->type == MEET_OTHER)
1669                         {
1670                                 infostream<<"Server: MEET_OTHER"<<std::endl;
1671                                 prof.add("MEET_OTHER", 1);
1672                                 for(core::map<v3s16, bool>::Iterator
1673                                                 i = event->modified_blocks.getIterator();
1674                                                 i.atEnd()==false; i++)
1675                                 {
1676                                         v3s16 p = i.getNode()->getKey();
1677                                         setBlockNotSent(p);
1678                                 }
1679                         }
1680                         else
1681                         {
1682                                 prof.add("unknown", 1);
1683                                 infostream<<"WARNING: Server: Unknown MapEditEvent "
1684                                                 <<((u32)event->type)<<std::endl;
1685                         }
1686                         
1687                         /*
1688                                 Set blocks not sent to far players
1689                         */
1690                         if(far_players.size() > 0)
1691                         {
1692                                 // Convert list format to that wanted by SetBlocksNotSent
1693                                 core::map<v3s16, MapBlock*> modified_blocks2;
1694                                 for(core::map<v3s16, bool>::Iterator
1695                                                 i = event->modified_blocks.getIterator();
1696                                                 i.atEnd()==false; i++)
1697                                 {
1698                                         v3s16 p = i.getNode()->getKey();
1699                                         modified_blocks2.insert(p,
1700                                                         m_env->getMap().getBlockNoCreateNoEx(p));
1701                                 }
1702                                 // Set blocks not sent
1703                                 for(core::list<u16>::Iterator
1704                                                 i = far_players.begin();
1705                                                 i != far_players.end(); i++)
1706                                 {
1707                                         u16 peer_id = *i;
1708                                         RemoteClient *client = getClient(peer_id);
1709                                         if(client==NULL)
1710                                                 continue;
1711                                         client->SetBlocksNotSent(modified_blocks2);
1712                                 }
1713                         }
1714
1715                         delete event;
1716
1717                         /*// Don't send too many at a time
1718                         count++;
1719                         if(count >= 1 && m_unsent_map_edit_queue.size() < 100)
1720                                 break;*/
1721                 }
1722
1723                 if(got_any_events)
1724                 {
1725                         infostream<<"Server: MapEditEvents:"<<std::endl;
1726                         prof.print(infostream);
1727                 }
1728                 
1729         }
1730
1731         /*
1732                 Send object positions
1733         */
1734         {
1735                 float &counter = m_objectdata_timer;
1736                 counter += dtime;
1737                 if(counter >= g_settings->getFloat("objectdata_interval"))
1738                 {
1739                         JMutexAutoLock lock1(m_env_mutex);
1740                         JMutexAutoLock lock2(m_con_mutex);
1741
1742                         //ScopeProfiler sp(g_profiler, "Server: sending player positions");
1743
1744                         SendObjectData(counter);
1745
1746                         counter = 0.0;
1747                 }
1748         }
1749         
1750         /*
1751                 Trigger emergethread (it somehow gets to a non-triggered but
1752                 bysy state sometimes)
1753         */
1754         {
1755                 float &counter = m_emergethread_trigger_timer;
1756                 counter += dtime;
1757                 if(counter >= 2.0)
1758                 {
1759                         counter = 0.0;
1760                         
1761                         m_emergethread.trigger();
1762                 }
1763         }
1764
1765         // Save map, players and auth stuff
1766         {
1767                 float &counter = m_savemap_timer;
1768                 counter += dtime;
1769                 if(counter >= g_settings->getFloat("server_map_save_interval"))
1770                 {
1771                         counter = 0.0;
1772
1773                         ScopeProfiler sp(g_profiler, "Server: saving stuff");
1774
1775                         // Auth stuff
1776                         if(m_authmanager.isModified())
1777                                 m_authmanager.save();
1778
1779                         //Bann stuff
1780                         if(m_banmanager.isModified())
1781                                 m_banmanager.save();
1782                         
1783                         // Map
1784                         JMutexAutoLock lock(m_env_mutex);
1785
1786                         /*// Unload unused data (delete from memory)
1787                         m_env->getMap().unloadUnusedData(
1788                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1789                                         */
1790                         /*u32 deleted_count = m_env->getMap().unloadUnusedData(
1791                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1792                                         */
1793
1794                         // Save only changed parts
1795                         m_env->getMap().save(true);
1796
1797                         /*if(deleted_count > 0)
1798                         {
1799                                 infostream<<"Server: Unloaded "<<deleted_count
1800                                                 <<" blocks from memory"<<std::endl;
1801                         }*/
1802
1803                         // Save players
1804                         m_env->serializePlayers(m_mapsavedir);
1805                         
1806                         // Save environment metadata
1807                         m_env->saveMeta(m_mapsavedir);
1808                 }
1809         }
1810 }
1811
1812 void Server::Receive()
1813 {
1814         DSTACK(__FUNCTION_NAME);
1815         SharedBuffer<u8> data;
1816         u16 peer_id;
1817         u32 datasize;
1818         try{
1819                 {
1820                         JMutexAutoLock conlock(m_con_mutex);
1821                         datasize = m_con.Receive(peer_id, data);
1822                 }
1823
1824                 // This has to be called so that the client list gets synced
1825                 // with the peer list of the connection
1826                 handlePeerChanges();
1827
1828                 ProcessData(*data, datasize, peer_id);
1829         }
1830         catch(con::InvalidIncomingDataException &e)
1831         {
1832                 infostream<<"Server::Receive(): "
1833                                 "InvalidIncomingDataException: what()="
1834                                 <<e.what()<<std::endl;
1835         }
1836         catch(con::PeerNotFoundException &e)
1837         {
1838                 //NOTE: This is not needed anymore
1839                 
1840                 // The peer has been disconnected.
1841                 // Find the associated player and remove it.
1842
1843                 /*JMutexAutoLock envlock(m_env_mutex);
1844
1845                 infostream<<"ServerThread: peer_id="<<peer_id
1846                                 <<" has apparently closed connection. "
1847                                 <<"Removing player."<<std::endl;
1848
1849                 m_env->removePlayer(peer_id);*/
1850         }
1851 }
1852
1853 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1854 {
1855         DSTACK(__FUNCTION_NAME);
1856         // Environment is locked first.
1857         JMutexAutoLock envlock(m_env_mutex);
1858         JMutexAutoLock conlock(m_con_mutex);
1859         
1860         try{
1861                 Address address = m_con.GetPeerAddress(peer_id);
1862
1863                 // drop player if is ip is banned
1864                 if(m_banmanager.isIpBanned(address.serializeString())){
1865                         SendAccessDenied(m_con, peer_id,
1866                                         L"Your ip is banned. Banned name was "
1867                                         +narrow_to_wide(m_banmanager.getBanName(
1868                                                 address.serializeString())));
1869                         m_con.DeletePeer(peer_id);
1870                         return;
1871                 }
1872         }
1873         catch(con::PeerNotFoundException &e)
1874         {
1875                 infostream<<"Server::ProcessData(): Cancelling: peer "
1876                                 <<peer_id<<" not found"<<std::endl;
1877                 return;
1878         }
1879
1880         u8 peer_ser_ver = getClient(peer_id)->serialization_version;
1881
1882         try
1883         {
1884
1885         if(datasize < 2)
1886                 return;
1887
1888         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1889         
1890         if(command == TOSERVER_INIT)
1891         {
1892                 // [0] u16 TOSERVER_INIT
1893                 // [2] u8 SER_FMT_VER_HIGHEST
1894                 // [3] u8[20] player_name
1895                 // [23] u8[28] password <--- can be sent without this, from old versions
1896
1897                 if(datasize < 2+1+PLAYERNAME_SIZE)
1898                         return;
1899
1900                 infostream<<"Server: Got TOSERVER_INIT from "
1901                                 <<peer_id<<std::endl;
1902
1903                 // First byte after command is maximum supported
1904                 // serialization version
1905                 u8 client_max = data[2];
1906                 u8 our_max = SER_FMT_VER_HIGHEST;
1907                 // Use the highest version supported by both
1908                 u8 deployed = core::min_(client_max, our_max);
1909                 // If it's lower than the lowest supported, give up.
1910                 if(deployed < SER_FMT_VER_LOWEST)
1911                         deployed = SER_FMT_VER_INVALID;
1912
1913                 //peer->serialization_version = deployed;
1914                 getClient(peer_id)->pending_serialization_version = deployed;
1915                 
1916                 if(deployed == SER_FMT_VER_INVALID)
1917                 {
1918                         infostream<<"Server: Cannot negotiate "
1919                                         "serialization version with peer "
1920                                         <<peer_id<<std::endl;
1921                         SendAccessDenied(m_con, peer_id,
1922                                         L"Your client is too old (map format)");
1923                         return;
1924                 }
1925                 
1926                 /*
1927                         Read and check network protocol version
1928                 */
1929
1930                 u16 net_proto_version = 0;
1931                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
1932                 {
1933                         net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
1934                 }
1935
1936                 getClient(peer_id)->net_proto_version = net_proto_version;
1937
1938                 if(net_proto_version == 0)
1939                 {
1940                         SendAccessDenied(m_con, peer_id,
1941                                         L"Your client is too old. Please upgrade.");
1942                         return;
1943                 }
1944                 
1945                 /* Uhh... this should actually be a warning but let's do it like this */
1946                 if(g_settings->getBool("strict_protocol_version_checking"))
1947                 {
1948                         if(net_proto_version < PROTOCOL_VERSION)
1949                         {
1950                                 SendAccessDenied(m_con, peer_id,
1951                                                 L"Your client is too old. Please upgrade.");
1952                                 return;
1953                         }
1954                 }
1955
1956                 /*
1957                         Set up player
1958                 */
1959                 
1960                 // Get player name
1961                 char playername[PLAYERNAME_SIZE];
1962                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
1963                 {
1964                         playername[i] = data[3+i];
1965                 }
1966                 playername[PLAYERNAME_SIZE-1] = 0;
1967                 
1968                 if(playername[0]=='\0')
1969                 {
1970                         infostream<<"Server: Player has empty name"<<std::endl;
1971                         SendAccessDenied(m_con, peer_id,
1972                                         L"Empty name");
1973                         return;
1974                 }
1975
1976                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1977                 {
1978                         infostream<<"Server: Player has invalid name"<<std::endl;
1979                         SendAccessDenied(m_con, peer_id,
1980                                         L"Name contains unallowed characters");
1981                         return;
1982                 }
1983
1984                 // Get password
1985                 char password[PASSWORD_SIZE];
1986                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
1987                 {
1988                         // old version - assume blank password
1989                         password[0] = 0;
1990                 }
1991                 else
1992                 {
1993                                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
1994                                 {
1995                                         password[i] = data[23+i];
1996                                 }
1997                                 password[PASSWORD_SIZE-1] = 0;
1998                 }
1999                 
2000                 std::string checkpwd;
2001                 if(m_authmanager.exists(playername))
2002                 {
2003                         checkpwd = m_authmanager.getPassword(playername);
2004                 }
2005                 else
2006                 {
2007                         checkpwd = g_settings->get("default_password");
2008                 }
2009                 
2010                 /*infostream<<"Server: Client gave password '"<<password
2011                                 <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
2012                 
2013                 if(password != checkpwd && m_authmanager.exists(playername))
2014                 {
2015                         infostream<<"Server: peer_id="<<peer_id
2016                                         <<": supplied invalid password for "
2017                                         <<playername<<std::endl;
2018                         SendAccessDenied(m_con, peer_id, L"Invalid password");
2019                         return;
2020                 }
2021                 
2022                 // Add player to auth manager
2023                 if(m_authmanager.exists(playername) == false)
2024                 {
2025                         infostream<<"Server: adding player "<<playername
2026                                         <<" to auth manager"<<std::endl;
2027                         m_authmanager.add(playername);
2028                         m_authmanager.setPassword(playername, checkpwd);
2029                         m_authmanager.setPrivs(playername,
2030                                         stringToPrivs(g_settings->get("default_privs")));
2031                         m_authmanager.save();
2032                 }
2033                 
2034                 // Enforce user limit.
2035                 // Don't enforce for users that have some admin right
2036                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2037                                 (m_authmanager.getPrivs(playername)
2038                                         & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
2039                                 playername != g_settings->get("name"))
2040                 {
2041                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2042                         return;
2043                 }
2044
2045                 // Get player
2046                 Player *player = emergePlayer(playername, password, peer_id);
2047
2048                 // If failed, cancel
2049                 if(player == NULL)
2050                 {
2051                         infostream<<"Server: peer_id="<<peer_id
2052                                         <<": failed to emerge player"<<std::endl;
2053                         return;
2054                 }
2055
2056                 /*
2057                         Answer with a TOCLIENT_INIT
2058                 */
2059                 {
2060                         SharedBuffer<u8> reply(2+1+6+8);
2061                         writeU16(&reply[0], TOCLIENT_INIT);
2062                         writeU8(&reply[2], deployed);
2063                         writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
2064                         writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
2065                         
2066                         // Send as reliable
2067                         m_con.Send(peer_id, 0, reply, true);
2068                 }
2069
2070                 /*
2071                         Send complete position information
2072                 */
2073                 SendMovePlayer(player);
2074
2075                 return;
2076         }
2077
2078         if(command == TOSERVER_INIT2)
2079         {
2080                 infostream<<"Server: Got TOSERVER_INIT2 from "
2081                                 <<peer_id<<std::endl;
2082
2083
2084                 getClient(peer_id)->serialization_version
2085                                 = getClient(peer_id)->pending_serialization_version;
2086
2087                 /*
2088                         Send some initialization data
2089                 */
2090                 
2091                 // Send player info to all players
2092                 SendPlayerInfos();
2093
2094                 // Send inventory to player
2095                 UpdateCrafting(peer_id);
2096                 SendInventory(peer_id);
2097
2098                 // Send player items to all players
2099                 SendPlayerItems();
2100
2101                 Player *player = m_env->getPlayer(peer_id);
2102
2103                 // Send HP
2104                 SendPlayerHP(player);
2105                 
2106                 // Send time of day
2107                 {
2108                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2109                                         m_env->getTimeOfDay());
2110                         m_con.Send(peer_id, 0, data, true);
2111                 }
2112                 
2113                 // Send information about server to player in chat
2114                 SendChatMessage(peer_id, getStatusString());
2115                 
2116                 // Send information about joining in chat
2117                 {
2118                         std::wstring name = L"unknown";
2119                         Player *player = m_env->getPlayer(peer_id);
2120                         if(player != NULL)
2121                                 name = narrow_to_wide(player->getName());
2122                         
2123                         std::wstring message;
2124                         message += L"*** ";
2125                         message += name;
2126                         message += L" joined game";
2127                         BroadcastChatMessage(message);
2128                 }
2129                 
2130                 // Warnings about protocol version can be issued here
2131                 if(getClient(peer_id)->net_proto_version < PROTOCOL_VERSION)
2132                 {
2133                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
2134                 }
2135
2136                 /*
2137                         Check HP, respawn if necessary
2138                 */
2139                 HandlePlayerHP(player, 0);
2140
2141                 /*
2142                         Print out action
2143                 */
2144                 {
2145                         std::ostringstream os(std::ios_base::binary);
2146                         for(core::map<u16, RemoteClient*>::Iterator
2147                                 i = m_clients.getIterator();
2148                                 i.atEnd() == false; i++)
2149                         {
2150                                 RemoteClient *client = i.getNode()->getValue();
2151                                 assert(client->peer_id == i.getNode()->getKey());
2152                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2153                                         continue;
2154                                 // Get player
2155                                 Player *player = m_env->getPlayer(client->peer_id);
2156                                 if(!player)
2157                                         continue;
2158                                 // Get name of player
2159                                 os<<player->getName()<<" ";
2160                         }
2161
2162                         actionstream<<player->getName()<<" joins game. List of players: "
2163                                         <<os.str()<<std::endl;
2164                 }
2165
2166                 return;
2167         }
2168
2169         if(peer_ser_ver == SER_FMT_VER_INVALID)
2170         {
2171                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2172                                 " serialization format invalid or not initialized."
2173                                 " Skipping incoming command="<<command<<std::endl;
2174                 return;
2175         }
2176         
2177         Player *player = m_env->getPlayer(peer_id);
2178
2179         if(player == NULL){
2180                 infostream<<"Server::ProcessData(): Cancelling: "
2181                                 "No player for peer_id="<<peer_id
2182                                 <<std::endl;
2183                 return;
2184         }
2185         if(command == TOSERVER_PLAYERPOS)
2186         {
2187                 if(datasize < 2+12+12+4+4)
2188                         return;
2189         
2190                 u32 start = 0;
2191                 v3s32 ps = readV3S32(&data[start+2]);
2192                 v3s32 ss = readV3S32(&data[start+2+12]);
2193                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2194                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2195                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2196                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2197                 pitch = wrapDegrees(pitch);
2198                 yaw = wrapDegrees(yaw);
2199
2200                 player->setPosition(position);
2201                 player->setSpeed(speed);
2202                 player->setPitch(pitch);
2203                 player->setYaw(yaw);
2204                 
2205                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2206                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2207                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2208         }
2209         else if(command == TOSERVER_GOTBLOCKS)
2210         {
2211                 if(datasize < 2+1)
2212                         return;
2213                 
2214                 /*
2215                         [0] u16 command
2216                         [2] u8 count
2217                         [3] v3s16 pos_0
2218                         [3+6] v3s16 pos_1
2219                         ...
2220                 */
2221
2222                 u16 count = data[2];
2223                 for(u16 i=0; i<count; i++)
2224                 {
2225                         if((s16)datasize < 2+1+(i+1)*6)
2226                                 throw con::InvalidIncomingDataException
2227                                         ("GOTBLOCKS length is too short");
2228                         v3s16 p = readV3S16(&data[2+1+i*6]);
2229                         /*infostream<<"Server: GOTBLOCKS ("
2230                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2231                         RemoteClient *client = getClient(peer_id);
2232                         client->GotBlock(p);
2233                 }
2234         }
2235         else if(command == TOSERVER_DELETEDBLOCKS)
2236         {
2237                 if(datasize < 2+1)
2238                         return;
2239                 
2240                 /*
2241                         [0] u16 command
2242                         [2] u8 count
2243                         [3] v3s16 pos_0
2244                         [3+6] v3s16 pos_1
2245                         ...
2246                 */
2247
2248                 u16 count = data[2];
2249                 for(u16 i=0; i<count; i++)
2250                 {
2251                         if((s16)datasize < 2+1+(i+1)*6)
2252                                 throw con::InvalidIncomingDataException
2253                                         ("DELETEDBLOCKS length is too short");
2254                         v3s16 p = readV3S16(&data[2+1+i*6]);
2255                         /*infostream<<"Server: DELETEDBLOCKS ("
2256                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2257                         RemoteClient *client = getClient(peer_id);
2258                         client->SetBlockNotSent(p);
2259                 }
2260         }
2261         else if(command == TOSERVER_CLICK_OBJECT)
2262         {
2263                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2264                 return;
2265         }
2266         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2267         {
2268                 if(datasize < 7)
2269                         return;
2270
2271                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2272                         return;
2273
2274                 /*
2275                         length: 7
2276                         [0] u16 command
2277                         [2] u8 button (0=left, 1=right)
2278                         [3] u16 id
2279                         [5] u16 item
2280                 */
2281                 u8 button = readU8(&data[2]);
2282                 u16 id = readS16(&data[3]);
2283                 u16 item_i = readU16(&data[5]);
2284         
2285                 ServerActiveObject *obj = m_env->getActiveObject(id);
2286
2287                 if(obj == NULL)
2288                 {
2289                         infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
2290                                         <<std::endl;
2291                         return;
2292                 }
2293
2294                 // Skip if object has been removed
2295                 if(obj->m_removed)
2296                         return;
2297                 
2298                 //TODO: Check that object is reasonably close
2299                 
2300                 // Left click, pick object up (usually)
2301                 if(button == 0)
2302                 {
2303                         /*
2304                                 Try creating inventory item
2305                         */
2306                         InventoryItem *item = obj->createPickedUpItem();
2307                         
2308                         if(item)
2309                         {
2310                                 InventoryList *ilist = player->inventory.getList("main");
2311                                 if(ilist != NULL)
2312                                 {
2313                                         actionstream<<player->getName()<<" picked up "
2314                                                         <<item->getName()<<std::endl;
2315                                         if(g_settings->getBool("creative_mode") == false)
2316                                         {
2317                                                 // Skip if inventory has no free space
2318                                                 if(ilist->roomForItem(item) == false)
2319                                                 {
2320                                                         infostream<<"Player inventory has no free space"<<std::endl;
2321                                                         return;
2322                                                 }
2323
2324                                                 // Add to inventory and send inventory
2325                                                 ilist->addItem(item);
2326                                                 UpdateCrafting(player->peer_id);
2327                                                 SendInventory(player->peer_id);
2328                                         }
2329
2330                                         // Remove object from environment
2331                                         obj->m_removed = true;
2332                                 }
2333                         }
2334                         else
2335                         {
2336                                 /*
2337                                         Item cannot be picked up. Punch it instead.
2338                                 */
2339
2340                                 actionstream<<player->getName()<<" punches object "
2341                                                 <<obj->getId()<<std::endl;
2342
2343                                 ToolItem *titem = NULL;
2344                                 std::string toolname = "";
2345
2346                                 InventoryList *mlist = player->inventory.getList("main");
2347                                 if(mlist != NULL)
2348                                 {
2349                                         InventoryItem *item = mlist->getItem(item_i);
2350                                         if(item && (std::string)item->getName() == "ToolItem")
2351                                         {
2352                                                 titem = (ToolItem*)item;
2353                                                 toolname = titem->getToolName();
2354                                         }
2355                                 }
2356
2357                                 v3f playerpos = player->getPosition();
2358                                 v3f objpos = obj->getBasePosition();
2359                                 v3f dir = (objpos - playerpos).normalize();
2360                                 
2361                                 u16 wear = obj->punch(toolname, dir, player->getName());
2362                                 
2363                                 if(titem)
2364                                 {
2365                                         bool weared_out = titem->addWear(wear);
2366                                         if(weared_out)
2367                                                 mlist->deleteItem(item_i);
2368                                         SendInventory(player->peer_id);
2369                                 }
2370                         }
2371                 }
2372                 // Right click, do something with object
2373                 if(button == 1)
2374                 {
2375                         actionstream<<player->getName()<<" right clicks object "
2376                                         <<obj->getId()<<std::endl;
2377
2378                         // Track hp changes super-crappily
2379                         u16 oldhp = player->hp;
2380                         
2381                         // Do stuff
2382                         obj->rightClick(player);
2383                         
2384                         // Send back stuff
2385                         if(player->hp != oldhp)
2386                         {
2387                                 SendPlayerHP(player);
2388                         }
2389                 }
2390         }
2391         else if(command == TOSERVER_GROUND_ACTION)
2392         {
2393                 if(datasize < 17)
2394                         return;
2395                 /*
2396                         length: 17
2397                         [0] u16 command
2398                         [2] u8 action
2399                         [3] v3s16 nodepos_undersurface
2400                         [9] v3s16 nodepos_abovesurface
2401                         [15] u16 item
2402                         actions:
2403                         0: start digging
2404                         1: place block
2405                         2: stop digging (all parameters ignored)
2406                         3: digging completed
2407                 */
2408                 u8 action = readU8(&data[2]);
2409                 v3s16 p_under;
2410                 p_under.X = readS16(&data[3]);
2411                 p_under.Y = readS16(&data[5]);
2412                 p_under.Z = readS16(&data[7]);
2413                 v3s16 p_over;
2414                 p_over.X = readS16(&data[9]);
2415                 p_over.Y = readS16(&data[11]);
2416                 p_over.Z = readS16(&data[13]);
2417                 u16 item_i = readU16(&data[15]);
2418
2419                 //TODO: Check that target is reasonably close
2420                 
2421                 /*
2422                         0: start digging
2423                 */
2424                 if(action == 0)
2425                 {
2426                         /*
2427                                 NOTE: This can be used in the future to check if
2428                                 somebody is cheating, by checking the timing.
2429                         */
2430                 } // action == 0
2431
2432                 /*
2433                         2: stop digging
2434                 */
2435                 else if(action == 2)
2436                 {
2437 #if 0
2438                         RemoteClient *client = getClient(peer_id);
2439                         JMutexAutoLock digmutex(client->m_dig_mutex);
2440                         client->m_dig_tool_item = -1;
2441 #endif
2442                 }
2443
2444                 /*
2445                         3: Digging completed
2446                 */
2447                 else if(action == 3)
2448                 {
2449                         // Mandatory parameter; actually used for nothing
2450                         core::map<v3s16, MapBlock*> modified_blocks;
2451
2452                         content_t material = CONTENT_IGNORE;
2453                         u8 mineral = MINERAL_NONE;
2454
2455                         bool cannot_remove_node = false;
2456
2457                         try
2458                         {
2459                                 MapNode n = m_env->getMap().getNode(p_under);
2460                                 // Get mineral
2461                                 mineral = n.getMineral();
2462                                 // Get material at position
2463                                 material = n.getContent();
2464                                 // If not yet cancelled
2465                                 if(cannot_remove_node == false)
2466                                 {
2467                                         // If it's not diggable, do nothing
2468                                         if(content_diggable(material) == false)
2469                                         {
2470                                                 infostream<<"Server: Not finishing digging: "
2471                                                                 <<"Node not diggable"
2472                                                                 <<std::endl;
2473                                                 cannot_remove_node = true;
2474                                         }
2475                                 }
2476                                 // If not yet cancelled
2477                                 if(cannot_remove_node == false)
2478                                 {
2479                                         // Get node metadata
2480                                         NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
2481                                         if(meta && meta->nodeRemovalDisabled() == true)
2482                                         {
2483                                                 infostream<<"Server: Not finishing digging: "
2484                                                                 <<"Node metadata disables removal"
2485                                                                 <<std::endl;
2486                                                 cannot_remove_node = true;
2487                                         }
2488                                 }
2489                         }
2490                         catch(InvalidPositionException &e)
2491                         {
2492                                 infostream<<"Server: Not finishing digging: Node not found."
2493                                                 <<" Adding block to emerge queue."
2494                                                 <<std::endl;
2495                                 m_emerge_queue.addBlock(peer_id,
2496                                                 getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2497                                 cannot_remove_node = true;
2498                         }
2499
2500                         // Make sure the player is allowed to do it
2501                         if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2502                         {
2503                                 infostream<<"Player "<<player->getName()<<" cannot remove node"
2504                                                 <<" because privileges are "<<getPlayerPrivs(player)
2505                                                 <<std::endl;
2506                                 cannot_remove_node = true;
2507                         }
2508
2509                         /*
2510                                 If node can't be removed, set block to be re-sent to
2511                                 client and quit.
2512                         */
2513                         if(cannot_remove_node)
2514                         {
2515                                 infostream<<"Server: Not finishing digging."<<std::endl;
2516
2517                                 // Client probably has wrong data.
2518                                 // Set block not sent, so that client will get
2519                                 // a valid one.
2520                                 infostream<<"Client "<<peer_id<<" tried to dig "
2521                                                 <<"node; but node cannot be removed."
2522                                                 <<" setting MapBlock not sent."<<std::endl;
2523                                 RemoteClient *client = getClient(peer_id);
2524                                 v3s16 blockpos = getNodeBlockPos(p_under);
2525                                 client->SetBlockNotSent(blockpos);
2526                                         
2527                                 return;
2528                         }
2529                         
2530                         actionstream<<player->getName()<<" digs "<<PP(p_under)
2531                                         <<", gets material "<<(int)material<<", mineral "
2532                                         <<(int)mineral<<std::endl;
2533                         
2534                         /*
2535                                 Send the removal to all close-by players.
2536                                 - If other player is close, send REMOVENODE
2537                                 - Otherwise set blocks not sent
2538                         */
2539                         core::list<u16> far_players;
2540                         sendRemoveNode(p_under, peer_id, &far_players, 30);
2541                         
2542                         /*
2543                                 Update and send inventory
2544                         */
2545
2546                         if(g_settings->getBool("creative_mode") == false)
2547                         {
2548                                 /*
2549                                         Wear out tool
2550                                 */
2551                                 InventoryList *mlist = player->inventory.getList("main");
2552                                 if(mlist != NULL)
2553                                 {
2554                                         InventoryItem *item = mlist->getItem(item_i);
2555                                         if(item && (std::string)item->getName() == "ToolItem")
2556                                         {
2557                                                 ToolItem *titem = (ToolItem*)item;
2558                                                 std::string toolname = titem->getToolName();
2559
2560                                                 // Get digging properties for material and tool
2561                                                 DiggingProperties prop =
2562                                                                 getDiggingProperties(material, toolname);
2563
2564                                                 if(prop.diggable == false)
2565                                                 {
2566                                                         infostream<<"Server: WARNING: Player digged"
2567                                                                         <<" with impossible material + tool"
2568                                                                         <<" combination"<<std::endl;
2569                                                 }
2570                                                 
2571                                                 bool weared_out = titem->addWear(prop.wear);
2572
2573                                                 if(weared_out)
2574                                                 {
2575                                                         mlist->deleteItem(item_i);
2576                                                 }
2577                                         }
2578                                 }
2579
2580                                 /*
2581                                         Add dug item to inventory
2582                                 */
2583
2584                                 InventoryItem *item = NULL;
2585
2586                                 if(mineral != MINERAL_NONE)
2587                                         item = getDiggedMineralItem(mineral);
2588                                 
2589                                 // If not mineral
2590                                 if(item == NULL)
2591                                 {
2592                                         std::string &dug_s = content_features(material).dug_item;
2593                                         if(dug_s != "")
2594                                         {
2595                                                 std::istringstream is(dug_s, std::ios::binary);
2596                                                 item = InventoryItem::deSerialize(is);
2597                                         }
2598                                 }
2599                                 
2600                                 if(item != NULL)
2601                                 {
2602                                         // Add a item to inventory
2603                                         player->inventory.addItem("main", item);
2604
2605                                         // Send inventory
2606                                         UpdateCrafting(player->peer_id);
2607                                         SendInventory(player->peer_id);
2608                                 }
2609
2610                                 item = NULL;
2611
2612                                 if(mineral != MINERAL_NONE)
2613                                   item = getDiggedMineralItem(mineral);
2614                         
2615                                 // If not mineral
2616                                 if(item == NULL)
2617                                 {
2618                                         std::string &extra_dug_s = content_features(material).extra_dug_item;
2619                                         s32 extra_rarity = content_features(material).extra_dug_item_rarity;
2620                                         if(extra_dug_s != "" && extra_rarity != 0
2621                                            && myrand() % extra_rarity == 0)
2622                                         {
2623                                                 std::istringstream is(extra_dug_s, std::ios::binary);
2624                                                 item = InventoryItem::deSerialize(is);
2625                                         }
2626                                 }
2627                         
2628                                 if(item != NULL)
2629                                 {
2630                                         // Add a item to inventory
2631                                         player->inventory.addItem("main", item);
2632
2633                                         // Send inventory
2634                                         UpdateCrafting(player->peer_id);
2635                                         SendInventory(player->peer_id);
2636                                 }
2637                         }
2638
2639                         /*
2640                                 Remove the node
2641                                 (this takes some time so it is done after the quick stuff)
2642                         */
2643                         {
2644                                 MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2645
2646                                 m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
2647                         }
2648                         /*
2649                                 Set blocks not sent to far players
2650                         */
2651                         for(core::list<u16>::Iterator
2652                                         i = far_players.begin();
2653                                         i != far_players.end(); i++)
2654                         {
2655                                 u16 peer_id = *i;
2656                                 RemoteClient *client = getClient(peer_id);
2657                                 if(client==NULL)
2658                                         continue;
2659                                 client->SetBlocksNotSent(modified_blocks);
2660                         }
2661                 }
2662                 
2663                 /*
2664                         1: place block
2665                 */
2666                 else if(action == 1)
2667                 {
2668
2669                         InventoryList *ilist = player->inventory.getList("main");
2670                         if(ilist == NULL)
2671                                 return;
2672
2673                         // Get item
2674                         InventoryItem *item = ilist->getItem(item_i);
2675                         
2676                         // If there is no item, it is not possible to add it anywhere
2677                         if(item == NULL)
2678                                 return;
2679                         
2680                         /*
2681                                 Handle material items
2682                         */
2683                         if(std::string("MaterialItem") == item->getName())
2684                         {
2685                                 try{
2686                                         // Don't add a node if this is not a free space
2687                                         MapNode n2 = m_env->getMap().getNode(p_over);
2688                                         bool no_enough_privs =
2689                                                         ((getPlayerPrivs(player) & PRIV_BUILD)==0);
2690                                         if(no_enough_privs)
2691                                                 infostream<<"Player "<<player->getName()<<" cannot add node"
2692                                                         <<" because privileges are "<<getPlayerPrivs(player)
2693                                                         <<std::endl;
2694
2695                                         if(content_features(n2).buildable_to == false
2696                                                 || no_enough_privs)
2697                                         {
2698                                                 // Client probably has wrong data.
2699                                                 // Set block not sent, so that client will get
2700                                                 // a valid one.
2701                                                 infostream<<"Client "<<peer_id<<" tried to place"
2702                                                                 <<" node in invalid position; setting"
2703                                                                 <<" MapBlock not sent."<<std::endl;
2704                                                 RemoteClient *client = getClient(peer_id);
2705                                                 v3s16 blockpos = getNodeBlockPos(p_over);
2706                                                 client->SetBlockNotSent(blockpos);
2707                                                 return;
2708                                         }
2709                                 }
2710                                 catch(InvalidPositionException &e)
2711                                 {
2712                                         infostream<<"Server: Ignoring ADDNODE: Node not found"
2713                                                         <<" Adding block to emerge queue."
2714                                                         <<std::endl;
2715                                         m_emerge_queue.addBlock(peer_id,
2716                                                         getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2717                                         return;
2718                                 }
2719
2720                                 // Reset build time counter
2721                                 getClient(peer_id)->m_time_from_building = 0.0;
2722                                 
2723                                 // Create node data
2724                                 MaterialItem *mitem = (MaterialItem*)item;
2725                                 MapNode n;
2726                                 n.setContent(mitem->getMaterial());
2727
2728                                 actionstream<<player->getName()<<" places material "
2729                                                 <<(int)mitem->getMaterial()
2730                                                 <<" at "<<PP(p_under)<<std::endl;
2731                         
2732                                 // Calculate direction for wall mounted stuff
2733                                 if(content_features(n).wall_mounted)
2734                                         n.param2 = packDir(p_under - p_over);
2735
2736                                 // Calculate the direction for furnaces and chests and stuff
2737                                 if(content_features(n).param_type == CPT_FACEDIR_SIMPLE)
2738                                 {
2739                                         v3f playerpos = player->getPosition();
2740                                         v3f blockpos = intToFloat(p_over, BS) - playerpos;
2741                                         blockpos = blockpos.normalize();
2742                                         n.param1 = 0;
2743                                         if (fabs(blockpos.X) > fabs(blockpos.Z)) {
2744                                                 if (blockpos.X < 0)
2745                                                         n.param1 = 3;
2746                                                 else
2747                                                         n.param1 = 1;
2748                                         } else {
2749                                                 if (blockpos.Z < 0)
2750                                                         n.param1 = 2;
2751                                                 else
2752                                                         n.param1 = 0;
2753                                         }
2754                                 }
2755
2756                                 /*
2757                                         Send to all close-by players
2758                                 */
2759                                 core::list<u16> far_players;
2760                                 sendAddNode(p_over, n, 0, &far_players, 30);
2761                                 
2762                                 /*
2763                                         Handle inventory
2764                                 */
2765                                 InventoryList *ilist = player->inventory.getList("main");
2766                                 if(g_settings->getBool("creative_mode") == false && ilist)
2767                                 {
2768                                         // Remove from inventory and send inventory
2769                                         if(mitem->getCount() == 1)
2770                                                 ilist->deleteItem(item_i);
2771                                         else
2772                                                 mitem->remove(1);
2773                                         // Send inventory
2774                                         UpdateCrafting(peer_id);
2775                                         SendInventory(peer_id);
2776                                 }
2777                                 
2778                                 /*
2779                                         Add node.
2780
2781                                         This takes some time so it is done after the quick stuff
2782                                 */
2783                                 core::map<v3s16, MapBlock*> modified_blocks;
2784                                 {
2785                                         MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2786
2787                                         std::string p_name = std::string(player->getName());
2788                                         m_env->getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
2789                                 }
2790                                 /*
2791                                         Set blocks not sent to far players
2792                                 */
2793                                 for(core::list<u16>::Iterator
2794                                                 i = far_players.begin();
2795                                                 i != far_players.end(); i++)
2796                                 {
2797                                         u16 peer_id = *i;
2798                                         RemoteClient *client = getClient(peer_id);
2799                                         if(client==NULL)
2800                                                 continue;
2801                                         client->SetBlocksNotSent(modified_blocks);
2802                                 }
2803
2804                                 /*
2805                                         Calculate special events
2806                                 */
2807                                 
2808                                 /*if(n.d == CONTENT_MESE)
2809                                 {
2810                                         u32 count = 0;
2811                                         for(s16 z=-1; z<=1; z++)
2812                                         for(s16 y=-1; y<=1; y++)
2813                                         for(s16 x=-1; x<=1; x++)
2814                                         {
2815                                                 
2816                                         }
2817                                 }*/
2818                         }
2819                         /*
2820                                 Place other item (not a block)
2821                         */
2822                         else
2823                         {
2824                                 v3s16 blockpos = getNodeBlockPos(p_over);
2825                                 
2826                                 /*
2827                                         Check that the block is loaded so that the item
2828                                         can properly be added to the static list too
2829                                 */
2830                                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
2831                                 if(block==NULL)
2832                                 {
2833                                         infostream<<"Error while placing object: "
2834                                                         "block not found"<<std::endl;
2835                                         return;
2836                                 }
2837
2838                                 /*
2839                                         If in creative mode, item dropping is disabled unless
2840                                         player has build privileges
2841                                 */
2842                                 if(g_settings->getBool("creative_mode") &&
2843                                         (getPlayerPrivs(player) & PRIV_BUILD) == 0)
2844                                 {
2845                                         infostream<<"Not allowing player to drop item: "
2846                                                         "creative mode and no build privs"<<std::endl;
2847                                         return;
2848                                 }
2849
2850                                 // Calculate a position for it
2851                                 v3f pos = intToFloat(p_over, BS);
2852                                 //pos.Y -= BS*0.45;
2853                                 pos.Y -= BS*0.25; // let it drop a bit
2854                                 // Randomize a bit
2855                                 pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2856                                 pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2857
2858                                 /*
2859                                         Create the object
2860                                 */
2861                                 ServerActiveObject *obj = item->createSAO(m_env, 0, pos);
2862
2863                                 if(obj == NULL)
2864                                 {
2865                                         infostream<<"WARNING: item resulted in NULL object, "
2866                                                         <<"not placing onto map"
2867                                                         <<std::endl;
2868                                 }
2869                                 else
2870                                 {
2871                                         actionstream<<player->getName()<<" places "<<item->getName()
2872                                                         <<" at "<<PP(p_over)<<std::endl;
2873                                 
2874                                         // Add the object to the environment
2875                                         m_env->addActiveObject(obj);
2876                                         
2877                                         infostream<<"Placed object"<<std::endl;
2878
2879                                         if(g_settings->getBool("creative_mode") == false)
2880                                         {
2881                                                 // Delete the right amount of items from the slot
2882                                                 u16 dropcount = item->getDropCount();
2883                                                 
2884                                                 // Delete item if all gone
2885                                                 if(item->getCount() <= dropcount)
2886                                                 {
2887                                                         if(item->getCount() < dropcount)
2888                                                                 infostream<<"WARNING: Server: dropped more items"
2889                                                                                 <<" than the slot contains"<<std::endl;
2890                                                         
2891                                                         InventoryList *ilist = player->inventory.getList("main");
2892                                                         if(ilist)
2893                                                                 // Remove from inventory and send inventory
2894                                                                 ilist->deleteItem(item_i);
2895                                                 }
2896                                                 // Else decrement it
2897                                                 else
2898                                                         item->remove(dropcount);
2899                                                 
2900                                                 // Send inventory
2901                                                 UpdateCrafting(peer_id);
2902                                                 SendInventory(peer_id);
2903                                         }
2904                                 }
2905                         }
2906
2907                 } // action == 1
2908
2909                 /*
2910                         Catch invalid actions
2911                 */
2912                 else
2913                 {
2914                         infostream<<"WARNING: Server: Invalid action "
2915                                         <<action<<std::endl;
2916                 }
2917         }
2918 #if 0
2919         else if(command == TOSERVER_RELEASE)
2920         {
2921                 if(datasize < 3)
2922                         return;
2923                 /*
2924                         length: 3
2925                         [0] u16 command
2926                         [2] u8 button
2927                 */
2928                 infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
2929         }
2930 #endif
2931         else if(command == TOSERVER_SIGNTEXT)
2932         {
2933                 infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
2934                                 <<std::endl;
2935                 return;
2936         }
2937         else if(command == TOSERVER_SIGNNODETEXT)
2938         {
2939                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2940                         return;
2941                 /*
2942                         u16 command
2943                         v3s16 p
2944                         u16 textlen
2945                         textdata
2946                 */
2947                 std::string datastring((char*)&data[2], datasize-2);
2948                 std::istringstream is(datastring, std::ios_base::binary);
2949                 u8 buf[6];
2950                 // Read stuff
2951                 is.read((char*)buf, 6);
2952                 v3s16 p = readV3S16(buf);
2953                 is.read((char*)buf, 2);
2954                 u16 textlen = readU16(buf);
2955                 std::string text;
2956                 for(u16 i=0; i<textlen; i++)
2957                 {
2958                         is.read((char*)buf, 1);
2959                         text += (char)buf[0];
2960                 }
2961
2962                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
2963                 if(!meta)
2964                         return;
2965                 if(meta->typeId() != CONTENT_SIGN_WALL)
2966                         return;
2967                 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
2968                 signmeta->setText(text);
2969                 
2970                 actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
2971                                 <<" at "<<PP(p)<<std::endl;
2972                                 
2973                 v3s16 blockpos = getNodeBlockPos(p);
2974                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
2975                 if(block)
2976                 {
2977                         block->setChangedFlag();
2978                 }
2979
2980                 for(core::map<u16, RemoteClient*>::Iterator
2981                         i = m_clients.getIterator();
2982                         i.atEnd()==false; i++)
2983                 {
2984                         RemoteClient *client = i.getNode()->getValue();
2985                         client->SetBlockNotSent(blockpos);
2986                 }
2987         }
2988         else if(command == TOSERVER_INVENTORY_ACTION)
2989         {
2990                 /*// Ignore inventory changes if in creative mode
2991                 if(g_settings->getBool("creative_mode") == true)
2992                 {
2993                         infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
2994                                         <<std::endl;
2995                         return;
2996                 }*/
2997                 // Strip command and create a stream
2998                 std::string datastring((char*)&data[2], datasize-2);
2999                 infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
3000                 std::istringstream is(datastring, std::ios_base::binary);
3001                 // Create an action
3002                 InventoryAction *a = InventoryAction::deSerialize(is);
3003                 if(a != NULL)
3004                 {
3005                         // Create context
3006                         InventoryContext c;
3007                         c.current_player = player;
3008
3009                         /*
3010                                 Handle craftresult specially if not in creative mode
3011                         */
3012                         bool disable_action = false;
3013                         if(a->getType() == IACTION_MOVE
3014                                         && g_settings->getBool("creative_mode") == false)
3015                         {
3016                                 IMoveAction *ma = (IMoveAction*)a;
3017                                 if(ma->to_inv == "current_player" &&
3018                                                 ma->from_inv == "current_player")
3019                                 {
3020                                         InventoryList *rlist = player->inventory.getList("craftresult");
3021                                         assert(rlist);
3022                                         InventoryList *clist = player->inventory.getList("craft");
3023                                         assert(clist);
3024                                         InventoryList *mlist = player->inventory.getList("main");
3025                                         assert(mlist);
3026                                         /*
3027                                                 Craftresult is no longer preview if something
3028                                                 is moved into it
3029                                         */
3030                                         if(ma->to_list == "craftresult"
3031                                                         && ma->from_list != "craftresult")
3032                                         {
3033                                                 // If it currently is a preview, remove
3034                                                 // its contents
3035                                                 if(player->craftresult_is_preview)
3036                                                 {
3037                                                         rlist->deleteItem(0);
3038                                                 }
3039                                                 player->craftresult_is_preview = false;
3040                                         }
3041                                         /*
3042                                                 Crafting takes place if this condition is true.
3043                                         */
3044                                         if(player->craftresult_is_preview &&
3045                                                         ma->from_list == "craftresult")
3046                                         {
3047                                                 player->craftresult_is_preview = false;
3048                                                 clist->decrementMaterials(1);
3049                                                 
3050                                                 /* Print out action */
3051                                                 InventoryList *list =
3052                                                                 player->inventory.getList("craftresult");
3053                                                 assert(list);
3054                                                 InventoryItem *item = list->getItem(0);
3055                                                 std::string itemname = "NULL";
3056                                                 if(item)
3057                                                         itemname = item->getName();
3058                                                 actionstream<<player->getName()<<" crafts "
3059                                                                 <<itemname<<std::endl;
3060                                         }
3061                                         /*
3062                                                 If the craftresult is placed on itself, move it to
3063                                                 main inventory instead of doing the action
3064                                         */
3065                                         if(ma->to_list == "craftresult"
3066                                                         && ma->from_list == "craftresult")
3067                                         {
3068                                                 disable_action = true;
3069                                                 
3070                                                 InventoryItem *item1 = rlist->changeItem(0, NULL);
3071                                                 mlist->addItem(item1);
3072                                         }
3073                                 }
3074                                 // Disallow moving items if not allowed to build
3075                                 else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
3076                                 {
3077                                         return;
3078                                 }
3079                                 // if it's a locking chest, only allow the owner or server admins to move items
3080                                 else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3081                                 {
3082                                         Strfnd fn(ma->from_inv);
3083                                         std::string id0 = fn.next(":");
3084                                         if(id0 == "nodemeta")
3085                                         {
3086                                                 v3s16 p;
3087                                                 p.X = stoi(fn.next(","));
3088                                                 p.Y = stoi(fn.next(","));
3089                                                 p.Z = stoi(fn.next(","));
3090                                                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3091                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3092                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3093                                                         if (lcm->getOwner() != player->getName())
3094                                                                 return;
3095                                                 }
3096                                         }
3097                                 }
3098                                 else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3099                                 {
3100                                         Strfnd fn(ma->to_inv);
3101                                         std::string id0 = fn.next(":");
3102                                         if(id0 == "nodemeta")
3103                                         {
3104                                                 v3s16 p;
3105                                                 p.X = stoi(fn.next(","));
3106                                                 p.Y = stoi(fn.next(","));
3107                                                 p.Z = stoi(fn.next(","));
3108                                                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3109                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3110                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3111                                                         if (lcm->getOwner() != player->getName())
3112                                                                 return;
3113                                                 }
3114                                         }
3115                                 }
3116                         }
3117                         
3118                         if(disable_action == false)
3119                         {
3120                                 // Feed action to player inventory
3121                                 a->apply(&c, this);
3122                                 // Eat the action
3123                                 delete a;
3124                         }
3125                         else
3126                         {
3127                                 // Send inventory
3128                                 UpdateCrafting(player->peer_id);
3129                                 SendInventory(player->peer_id);
3130                         }
3131                 }
3132                 else
3133                 {
3134                         infostream<<"TOSERVER_INVENTORY_ACTION: "
3135                                         <<"InventoryAction::deSerialize() returned NULL"
3136                                         <<std::endl;
3137                 }
3138         }
3139         else if(command == TOSERVER_CHAT_MESSAGE)
3140         {
3141                 /*
3142                         u16 command
3143                         u16 length
3144                         wstring message
3145                 */
3146                 u8 buf[6];
3147                 std::string datastring((char*)&data[2], datasize-2);
3148                 std::istringstream is(datastring, std::ios_base::binary);
3149                 
3150                 // Read stuff
3151                 is.read((char*)buf, 2);
3152                 u16 len = readU16(buf);
3153                 
3154                 std::wstring message;
3155                 for(u16 i=0; i<len; i++)
3156                 {
3157                         is.read((char*)buf, 2);
3158                         message += (wchar_t)readU16(buf);
3159                 }
3160
3161                 // Get player name of this client
3162                 std::wstring name = narrow_to_wide(player->getName());
3163                 
3164                 // Line to send to players
3165                 std::wstring line;
3166                 // Whether to send to the player that sent the line
3167                 bool send_to_sender = false;
3168                 // Whether to send to other players
3169                 bool send_to_others = false;
3170                 
3171                 // Local player gets all privileges regardless of
3172                 // what's set on their account.
3173                 u64 privs = getPlayerPrivs(player);
3174
3175                 // Parse commands
3176                 if(message[0] == L'/')
3177                 {
3178                         size_t strip_size = 1;
3179                         if (message[1] == L'#') // support old-style commans
3180                                 ++strip_size;
3181                         message = message.substr(strip_size);
3182
3183                         WStrfnd f1(message);
3184                         f1.next(L" "); // Skip over /#whatever
3185                         std::wstring paramstring = f1.next(L"");
3186
3187                         ServerCommandContext *ctx = new ServerCommandContext(
3188                                 str_split(message, L' '),
3189                                 paramstring,
3190                                 this,
3191                                 m_env,
3192                                 player,
3193                                 privs);
3194
3195                         std::wstring reply(processServerCommand(ctx));
3196                         send_to_sender = ctx->flags & SEND_TO_SENDER;
3197                         send_to_others = ctx->flags & SEND_TO_OTHERS;
3198
3199                         if (ctx->flags & SEND_NO_PREFIX)
3200                                 line += reply;
3201                         else
3202                                 line += L"Server: " + reply;
3203
3204                         delete ctx;
3205
3206                 }
3207                 else
3208                 {
3209                         if(privs & PRIV_SHOUT)
3210                         {
3211                                 line += L"<";
3212                                 line += name;
3213                                 line += L"> ";
3214                                 line += message;
3215                                 send_to_others = true;
3216                         }
3217                         else
3218                         {
3219                                 line += L"Server: You are not allowed to shout";
3220                                 send_to_sender = true;
3221                         }
3222                 }
3223                 
3224                 if(line != L"")
3225                 {
3226                         if(send_to_others)
3227                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
3228
3229                         /*
3230                                 Send the message to clients
3231                         */
3232                         for(core::map<u16, RemoteClient*>::Iterator
3233                                 i = m_clients.getIterator();
3234                                 i.atEnd() == false; i++)
3235                         {
3236                                 // Get client and check that it is valid
3237                                 RemoteClient *client = i.getNode()->getValue();
3238                                 assert(client->peer_id == i.getNode()->getKey());
3239                                 if(client->serialization_version == SER_FMT_VER_INVALID)
3240                                         continue;
3241
3242                                 // Filter recipient
3243                                 bool sender_selected = (peer_id == client->peer_id);
3244                                 if(sender_selected == true && send_to_sender == false)
3245                                         continue;
3246                                 if(sender_selected == false && send_to_others == false)
3247                                         continue;
3248
3249                                 SendChatMessage(client->peer_id, line);
3250                         }
3251                 }
3252         }
3253         else if(command == TOSERVER_DAMAGE)
3254         {
3255                 std::string datastring((char*)&data[2], datasize-2);
3256                 std::istringstream is(datastring, std::ios_base::binary);
3257                 u8 damage = readU8(is);
3258
3259                 if(g_settings->getBool("enable_damage"))
3260                 {
3261                         actionstream<<player->getName()<<" damaged by "
3262                                         <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
3263                                         <<std::endl;
3264                                 
3265                         HandlePlayerHP(player, damage);
3266                 }
3267                 else
3268                 {
3269                         SendPlayerHP(player);
3270                 }
3271         }
3272         else if(command == TOSERVER_PASSWORD)
3273         {
3274                 /*
3275                         [0] u16 TOSERVER_PASSWORD
3276                         [2] u8[28] old password
3277                         [30] u8[28] new password
3278                 */
3279
3280                 if(datasize != 2+PASSWORD_SIZE*2)
3281                         return;
3282                 /*char password[PASSWORD_SIZE];
3283                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3284                         password[i] = data[2+i];
3285                 password[PASSWORD_SIZE-1] = 0;*/
3286                 std::string oldpwd;
3287                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3288                 {
3289                         char c = data[2+i];
3290                         if(c == 0)
3291                                 break;
3292                         oldpwd += c;
3293                 }
3294                 std::string newpwd;
3295                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3296                 {
3297                         char c = data[2+PASSWORD_SIZE+i];
3298                         if(c == 0)
3299                                 break;
3300                         newpwd += c;
3301                 }
3302
3303                 infostream<<"Server: Client requests a password change from "
3304                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
3305
3306                 std::string playername = player->getName();
3307
3308                 if(m_authmanager.exists(playername) == false)
3309                 {
3310                         infostream<<"Server: playername not found in authmanager"<<std::endl;
3311                         // Wrong old password supplied!!
3312                         SendChatMessage(peer_id, L"playername not found in authmanager");
3313                         return;
3314                 }
3315
3316                 std::string checkpwd = m_authmanager.getPassword(playername);
3317
3318                 if(oldpwd != checkpwd)
3319                 {
3320                         infostream<<"Server: invalid old password"<<std::endl;
3321                         // Wrong old password supplied!!
3322                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
3323                         return;
3324                 }
3325
3326                 actionstream<<player->getName()<<" changes password"<<std::endl;
3327
3328                 m_authmanager.setPassword(playername, newpwd);
3329                 
3330                 infostream<<"Server: password change successful for "<<playername
3331                                 <<std::endl;
3332                 SendChatMessage(peer_id, L"Password change successful");
3333         }
3334         else if(command == TOSERVER_PLAYERITEM)
3335         {
3336                 if (datasize < 2+2)
3337                         return;
3338
3339                 u16 item = readU16(&data[2]);
3340                 player->wieldItem(item);
3341                 SendWieldedItem(player);
3342         }
3343         else if(command == TOSERVER_RESPAWN)
3344         {
3345                 if(player->hp != 0)
3346                         return;
3347                 
3348                 RespawnPlayer(player);
3349                 
3350                 actionstream<<player->getName()<<" respawns at "
3351                                 <<PP(player->getPosition()/BS)<<std::endl;
3352         }
3353         else
3354         {
3355                 infostream<<"Server::ProcessData(): Ignoring "
3356                                 "unknown command "<<command<<std::endl;
3357         }
3358         
3359         } //try
3360         catch(SendFailedException &e)
3361         {
3362                 errorstream<<"Server::ProcessData(): SendFailedException: "
3363                                 <<"what="<<e.what()
3364                                 <<std::endl;
3365         }
3366 }
3367
3368 void Server::onMapEditEvent(MapEditEvent *event)
3369 {
3370         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3371         if(m_ignore_map_edit_events)
3372                 return;
3373         MapEditEvent *e = event->clone();
3374         m_unsent_map_edit_queue.push_back(e);
3375 }
3376
3377 Inventory* Server::getInventory(InventoryContext *c, std::string id)
3378 {
3379         if(id == "current_player")
3380         {
3381                 assert(c->current_player);
3382                 return &(c->current_player->inventory);
3383         }
3384         
3385         Strfnd fn(id);
3386         std::string id0 = fn.next(":");
3387
3388         if(id0 == "nodemeta")
3389         {
3390                 v3s16 p;
3391                 p.X = stoi(fn.next(","));
3392                 p.Y = stoi(fn.next(","));
3393                 p.Z = stoi(fn.next(","));
3394                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3395                 if(meta)
3396                         return meta->getInventory();
3397                 infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
3398                                 <<"no metadata found"<<std::endl;
3399                 return NULL;
3400         }
3401
3402         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3403         return NULL;
3404 }
3405 void Server::inventoryModified(InventoryContext *c, std::string id)
3406 {
3407         if(id == "current_player")
3408         {
3409                 assert(c->current_player);
3410                 // Send inventory
3411                 UpdateCrafting(c->current_player->peer_id);
3412                 SendInventory(c->current_player->peer_id);
3413                 return;
3414         }
3415         
3416         Strfnd fn(id);
3417         std::string id0 = fn.next(":");
3418
3419         if(id0 == "nodemeta")
3420         {
3421                 v3s16 p;
3422                 p.X = stoi(fn.next(","));
3423                 p.Y = stoi(fn.next(","));
3424                 p.Z = stoi(fn.next(","));
3425                 v3s16 blockpos = getNodeBlockPos(p);
3426
3427                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3428                 if(meta)
3429                         meta->inventoryModified();
3430
3431                 for(core::map<u16, RemoteClient*>::Iterator
3432                         i = m_clients.getIterator();
3433                         i.atEnd()==false; i++)
3434                 {
3435                         RemoteClient *client = i.getNode()->getValue();
3436                         client->SetBlockNotSent(blockpos);
3437                 }
3438
3439                 return;
3440         }
3441
3442         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3443 }
3444
3445 core::list<PlayerInfo> Server::getPlayerInfo()
3446 {
3447         DSTACK(__FUNCTION_NAME);
3448         JMutexAutoLock envlock(m_env_mutex);
3449         JMutexAutoLock conlock(m_con_mutex);
3450         
3451         core::list<PlayerInfo> list;
3452
3453         core::list<Player*> players = m_env->getPlayers();
3454         
3455         core::list<Player*>::Iterator i;
3456         for(i = players.begin();
3457                         i != players.end(); i++)
3458         {
3459                 PlayerInfo info;
3460
3461                 Player *player = *i;
3462
3463                 try{
3464                         // Copy info from connection to info struct
3465                         info.id = player->peer_id;
3466                         info.address = m_con.GetPeerAddress(player->peer_id);
3467                         info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
3468                 }
3469                 catch(con::PeerNotFoundException &e)
3470                 {
3471                         // Set dummy peer info
3472                         info.id = 0;
3473                         info.address = Address(0,0,0,0,0);
3474                         info.avg_rtt = 0.0;
3475                 }
3476
3477                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3478                 info.position = player->getPosition();
3479
3480                 list.push_back(info);
3481         }
3482
3483         return list;
3484 }
3485
3486
3487 void Server::peerAdded(con::Peer *peer)
3488 {
3489         DSTACK(__FUNCTION_NAME);
3490         infostream<<"Server::peerAdded(): peer->id="
3491                         <<peer->id<<std::endl;
3492         
3493         PeerChange c;
3494         c.type = PEER_ADDED;
3495         c.peer_id = peer->id;
3496         c.timeout = false;
3497         m_peer_change_queue.push_back(c);
3498 }
3499
3500 void Server::deletingPeer(con::Peer *peer, bool timeout)
3501 {
3502         DSTACK(__FUNCTION_NAME);
3503         infostream<<"Server::deletingPeer(): peer->id="
3504                         <<peer->id<<", timeout="<<timeout<<std::endl;
3505         
3506         PeerChange c;
3507         c.type = PEER_REMOVED;
3508         c.peer_id = peer->id;
3509         c.timeout = timeout;
3510         m_peer_change_queue.push_back(c);
3511 }
3512
3513 /*
3514         Static send methods
3515 */
3516
3517 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3518 {
3519         DSTACK(__FUNCTION_NAME);
3520         std::ostringstream os(std::ios_base::binary);
3521
3522         writeU16(os, TOCLIENT_HP);
3523         writeU8(os, hp);
3524
3525         // Make data buffer
3526         std::string s = os.str();
3527         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3528         // Send as reliable
3529         con.Send(peer_id, 0, data, true);
3530 }
3531
3532 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3533                 const std::wstring &reason)
3534 {
3535         DSTACK(__FUNCTION_NAME);
3536         std::ostringstream os(std::ios_base::binary);
3537
3538         writeU16(os, TOCLIENT_ACCESS_DENIED);
3539         os<<serializeWideString(reason);
3540
3541         // Make data buffer
3542         std::string s = os.str();
3543         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3544         // Send as reliable
3545         con.Send(peer_id, 0, data, true);
3546 }
3547
3548 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3549                 bool set_camera_point_target, v3f camera_point_target)
3550 {
3551         DSTACK(__FUNCTION_NAME);
3552         std::ostringstream os(std::ios_base::binary);
3553
3554         writeU16(os, TOCLIENT_DEATHSCREEN);
3555         writeU8(os, set_camera_point_target);
3556         writeV3F1000(os, camera_point_target);
3557
3558         // Make data buffer
3559         std::string s = os.str();
3560         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3561         // Send as reliable
3562         con.Send(peer_id, 0, data, true);
3563 }
3564
3565 /*
3566         Non-static send methods
3567 */
3568
3569 void Server::SendObjectData(float dtime)
3570 {
3571         DSTACK(__FUNCTION_NAME);
3572
3573         core::map<v3s16, bool> stepped_blocks;
3574         
3575         for(core::map<u16, RemoteClient*>::Iterator
3576                 i = m_clients.getIterator();
3577                 i.atEnd() == false; i++)
3578         {
3579                 u16 peer_id = i.getNode()->getKey();
3580                 RemoteClient *client = i.getNode()->getValue();
3581                 assert(client->peer_id == peer_id);
3582                 
3583                 if(client->serialization_version == SER_FMT_VER_INVALID)
3584                         continue;
3585                 
3586                 client->SendObjectData(this, dtime, stepped_blocks);
3587         }
3588 }
3589
3590 void Server::SendPlayerInfos()
3591 {
3592         DSTACK(__FUNCTION_NAME);
3593
3594         //JMutexAutoLock envlock(m_env_mutex);
3595         
3596         // Get connected players
3597         core::list<Player*> players = m_env->getPlayers(true);
3598         
3599         u32 player_count = players.getSize();
3600         u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
3601
3602         SharedBuffer<u8> data(datasize);
3603         writeU16(&data[0], TOCLIENT_PLAYERINFO);
3604         
3605         u32 start = 2;
3606         core::list<Player*>::Iterator i;
3607         for(i = players.begin();
3608                         i != players.end(); i++)
3609         {
3610                 Player *player = *i;
3611
3612                 /*infostream<<"Server sending player info for player with "
3613                                 "peer_id="<<player->peer_id<<std::endl;*/
3614                 
3615                 writeU16(&data[start], player->peer_id);
3616                 memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
3617                 snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
3618                 start += 2+PLAYERNAME_SIZE;
3619         }
3620
3621         //JMutexAutoLock conlock(m_con_mutex);
3622
3623         // Send as reliable
3624         m_con.SendToAll(0, data, true);
3625 }
3626
3627 void Server::SendInventory(u16 peer_id)
3628 {
3629         DSTACK(__FUNCTION_NAME);
3630         
3631         Player* player = m_env->getPlayer(peer_id);
3632         assert(player);
3633
3634         /*
3635                 Serialize it
3636         */
3637
3638         std::ostringstream os;
3639         //os.imbue(std::locale("C"));
3640
3641         player->inventory.serialize(os);
3642
3643         std::string s = os.str();
3644         
3645         SharedBuffer<u8> data(s.size()+2);
3646         writeU16(&data[0], TOCLIENT_INVENTORY);
3647         memcpy(&data[2], s.c_str(), s.size());
3648         
3649         // Send as reliable
3650         m_con.Send(peer_id, 0, data, true);
3651 }
3652
3653 std::string getWieldedItemString(const Player *player)
3654 {
3655         const InventoryItem *item = player->getWieldItem();
3656         if (item == NULL)
3657                 return std::string("");
3658         std::ostringstream os(std::ios_base::binary);
3659         item->serialize(os);
3660         return os.str();
3661 }
3662
3663 void Server::SendWieldedItem(const Player* player)
3664 {
3665         DSTACK(__FUNCTION_NAME);
3666
3667         assert(player);
3668
3669         std::ostringstream os(std::ios_base::binary);
3670
3671         writeU16(os, TOCLIENT_PLAYERITEM);
3672         writeU16(os, 1);
3673         writeU16(os, player->peer_id);
3674         os<<serializeString(getWieldedItemString(player));
3675
3676         // Make data buffer
3677         std::string s = os.str();
3678         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3679
3680         m_con.SendToAll(0, data, true);
3681 }
3682
3683 void Server::SendPlayerItems()
3684 {
3685         DSTACK(__FUNCTION_NAME);
3686
3687         std::ostringstream os(std::ios_base::binary);
3688         core::list<Player *> players = m_env->getPlayers(true);
3689
3690         writeU16(os, TOCLIENT_PLAYERITEM);
3691         writeU16(os, players.size());
3692         core::list<Player *>::Iterator i;
3693         for(i = players.begin(); i != players.end(); ++i)
3694         {
3695                 Player *p = *i;
3696                 writeU16(os, p->peer_id);
3697                 os<<serializeString(getWieldedItemString(p));
3698         }
3699
3700         // Make data buffer
3701         std::string s = os.str();
3702         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3703
3704         m_con.SendToAll(0, data, true);
3705 }
3706
3707 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3708 {
3709         DSTACK(__FUNCTION_NAME);
3710         
3711         std::ostringstream os(std::ios_base::binary);
3712         u8 buf[12];
3713         
3714         // Write command
3715         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3716         os.write((char*)buf, 2);
3717         
3718         // Write length
3719         writeU16(buf, message.size());
3720         os.write((char*)buf, 2);
3721         
3722         // Write string
3723         for(u32 i=0; i<message.size(); i++)
3724         {
3725                 u16 w = message[i];
3726                 writeU16(buf, w);
3727                 os.write((char*)buf, 2);
3728         }
3729         
3730         // Make data buffer
3731         std::string s = os.str();
3732         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3733         // Send as reliable
3734         m_con.Send(peer_id, 0, data, true);
3735 }
3736
3737 void Server::BroadcastChatMessage(const std::wstring &message)
3738 {
3739         for(core::map<u16, RemoteClient*>::Iterator
3740                 i = m_clients.getIterator();
3741                 i.atEnd() == false; i++)
3742         {
3743                 // Get client and check that it is valid
3744                 RemoteClient *client = i.getNode()->getValue();
3745                 assert(client->peer_id == i.getNode()->getKey());
3746                 if(client->serialization_version == SER_FMT_VER_INVALID)
3747                         continue;
3748
3749                 SendChatMessage(client->peer_id, message);
3750         }
3751 }
3752
3753 void Server::SendPlayerHP(Player *player)
3754 {
3755         SendHP(m_con, player->peer_id, player->hp);
3756 }
3757
3758 void Server::SendMovePlayer(Player *player)
3759 {
3760         DSTACK(__FUNCTION_NAME);
3761         std::ostringstream os(std::ios_base::binary);
3762
3763         writeU16(os, TOCLIENT_MOVE_PLAYER);
3764         writeV3F1000(os, player->getPosition());
3765         writeF1000(os, player->getPitch());
3766         writeF1000(os, player->getYaw());
3767         
3768         {
3769                 v3f pos = player->getPosition();
3770                 f32 pitch = player->getPitch();
3771                 f32 yaw = player->getYaw();
3772                 infostream<<"Server sending TOCLIENT_MOVE_PLAYER"
3773                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3774                                 <<" pitch="<<pitch
3775                                 <<" yaw="<<yaw
3776                                 <<std::endl;
3777         }
3778
3779         // Make data buffer
3780         std::string s = os.str();
3781         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3782         // Send as reliable
3783         m_con.Send(player->peer_id, 0, data, true);
3784 }
3785
3786 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3787         core::list<u16> *far_players, float far_d_nodes)
3788 {
3789         float maxd = far_d_nodes*BS;
3790         v3f p_f = intToFloat(p, BS);
3791
3792         // Create packet
3793         u32 replysize = 8;
3794         SharedBuffer<u8> reply(replysize);
3795         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3796         writeS16(&reply[2], p.X);
3797         writeS16(&reply[4], p.Y);
3798         writeS16(&reply[6], p.Z);
3799
3800         for(core::map<u16, RemoteClient*>::Iterator
3801                 i = m_clients.getIterator();
3802                 i.atEnd() == false; i++)
3803         {
3804                 // Get client and check that it is valid
3805                 RemoteClient *client = i.getNode()->getValue();
3806                 assert(client->peer_id == i.getNode()->getKey());
3807                 if(client->serialization_version == SER_FMT_VER_INVALID)
3808                         continue;
3809
3810                 // Don't send if it's the same one
3811                 if(client->peer_id == ignore_id)
3812                         continue;
3813                 
3814                 if(far_players)
3815                 {
3816                         // Get player
3817                         Player *player = m_env->getPlayer(client->peer_id);
3818                         if(player)
3819                         {
3820                                 // If player is far away, only set modified blocks not sent
3821                                 v3f player_pos = player->getPosition();
3822                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3823                                 {
3824                                         far_players->push_back(client->peer_id);
3825                                         continue;
3826                                 }
3827                         }
3828                 }
3829
3830                 // Send as reliable
3831                 m_con.Send(client->peer_id, 0, reply, true);
3832         }
3833 }
3834
3835 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3836                 core::list<u16> *far_players, float far_d_nodes)
3837 {
3838         float maxd = far_d_nodes*BS;
3839         v3f p_f = intToFloat(p, BS);
3840
3841         for(core::map<u16, RemoteClient*>::Iterator
3842                 i = m_clients.getIterator();
3843                 i.atEnd() == false; i++)
3844         {
3845                 // Get client and check that it is valid
3846                 RemoteClient *client = i.getNode()->getValue();
3847                 assert(client->peer_id == i.getNode()->getKey());
3848                 if(client->serialization_version == SER_FMT_VER_INVALID)
3849                         continue;
3850
3851                 // Don't send if it's the same one
3852                 if(client->peer_id == ignore_id)
3853                         continue;
3854
3855                 if(far_players)
3856                 {
3857                         // Get player
3858                         Player *player = m_env->getPlayer(client->peer_id);
3859                         if(player)
3860                         {
3861                                 // If player is far away, only set modified blocks not sent
3862                                 v3f player_pos = player->getPosition();
3863                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3864                                 {
3865                                         far_players->push_back(client->peer_id);
3866                                         continue;
3867                                 }
3868                         }
3869                 }
3870
3871                 // Create packet
3872                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
3873                 SharedBuffer<u8> reply(replysize);
3874                 writeU16(&reply[0], TOCLIENT_ADDNODE);
3875                 writeS16(&reply[2], p.X);
3876                 writeS16(&reply[4], p.Y);
3877                 writeS16(&reply[6], p.Z);
3878                 n.serialize(&reply[8], client->serialization_version);
3879
3880                 // Send as reliable
3881                 m_con.Send(client->peer_id, 0, reply, true);
3882         }
3883 }
3884
3885 void Server::setBlockNotSent(v3s16 p)
3886 {
3887         for(core::map<u16, RemoteClient*>::Iterator
3888                 i = m_clients.getIterator();
3889                 i.atEnd()==false; i++)
3890         {
3891                 RemoteClient *client = i.getNode()->getValue();
3892                 client->SetBlockNotSent(p);
3893         }
3894 }
3895
3896 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
3897 {
3898         DSTACK(__FUNCTION_NAME);
3899
3900         v3s16 p = block->getPos();
3901         
3902 #if 0
3903         // Analyze it a bit
3904         bool completely_air = true;
3905         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
3906         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
3907         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
3908         {
3909                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
3910                 {
3911                         completely_air = false;
3912                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
3913                 }
3914         }
3915
3916         // Print result
3917         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
3918         if(completely_air)
3919                 infostream<<"[completely air] ";
3920         infostream<<std::endl;
3921 #endif
3922
3923         /*
3924                 Create a packet with the block in the right format
3925         */
3926         
3927         std::ostringstream os(std::ios_base::binary);
3928         block->serialize(os, ver);
3929         std::string s = os.str();
3930         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
3931
3932         u32 replysize = 8 + blockdata.getSize();
3933         SharedBuffer<u8> reply(replysize);
3934         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
3935         writeS16(&reply[2], p.X);
3936         writeS16(&reply[4], p.Y);
3937         writeS16(&reply[6], p.Z);
3938         memcpy(&reply[8], *blockdata, blockdata.getSize());
3939
3940         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
3941                         <<":  \tpacket size: "<<replysize<<std::endl;*/
3942         
3943         /*
3944                 Send packet
3945         */
3946         m_con.Send(peer_id, 1, reply, true);
3947 }
3948
3949 void Server::SendBlocks(float dtime)
3950 {
3951         DSTACK(__FUNCTION_NAME);
3952
3953         JMutexAutoLock envlock(m_env_mutex);
3954         JMutexAutoLock conlock(m_con_mutex);
3955
3956         //TimeTaker timer("Server::SendBlocks");
3957
3958         core::array<PrioritySortedBlockTransfer> queue;
3959
3960         s32 total_sending = 0;
3961         
3962         {
3963                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
3964
3965                 for(core::map<u16, RemoteClient*>::Iterator
3966                         i = m_clients.getIterator();
3967                         i.atEnd() == false; i++)
3968                 {
3969                         RemoteClient *client = i.getNode()->getValue();
3970                         assert(client->peer_id == i.getNode()->getKey());
3971
3972                         total_sending += client->SendingCount();
3973                         
3974                         if(client->serialization_version == SER_FMT_VER_INVALID)
3975                                 continue;
3976                         
3977                         client->GetNextBlocks(this, dtime, queue);
3978                 }
3979         }
3980
3981         // Sort.
3982         // Lowest priority number comes first.
3983         // Lowest is most important.
3984         queue.sort();
3985
3986         for(u32 i=0; i<queue.size(); i++)
3987         {
3988                 //TODO: Calculate limit dynamically
3989                 if(total_sending >= g_settings->getS32
3990                                 ("max_simultaneous_block_sends_server_total"))
3991                         break;
3992                 
3993                 PrioritySortedBlockTransfer q = queue[i];
3994
3995                 MapBlock *block = NULL;
3996                 try
3997                 {
3998                         block = m_env->getMap().getBlockNoCreate(q.pos);
3999                 }
4000                 catch(InvalidPositionException &e)
4001                 {
4002                         continue;
4003                 }
4004
4005                 RemoteClient *client = getClient(q.peer_id);
4006
4007                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
4008
4009                 client->SentBlock(q.pos);
4010
4011                 total_sending++;
4012         }
4013 }
4014
4015 /*
4016         Something random
4017 */
4018
4019 void Server::HandlePlayerHP(Player *player, s16 damage)
4020 {
4021         if(player->hp > damage)
4022         {
4023                 player->hp -= damage;
4024                 SendPlayerHP(player);
4025         }
4026         else
4027         {
4028                 infostream<<"Server::HandlePlayerHP(): Player "
4029                                 <<player->getName()<<" dies"<<std::endl;
4030                 
4031                 player->hp = 0;
4032                 
4033                 //TODO: Throw items around
4034                 
4035                 // Handle players that are not connected
4036                 if(player->peer_id == PEER_ID_INEXISTENT){
4037                         RespawnPlayer(player);
4038                         return;
4039                 }
4040
4041                 SendPlayerHP(player);
4042                 
4043                 RemoteClient *client = getClient(player->peer_id);
4044                 if(client->net_proto_version >= 3)
4045                 {
4046                         SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
4047                 }
4048                 else
4049                 {
4050                         RespawnPlayer(player);
4051                 }
4052         }
4053 }
4054
4055 void Server::RespawnPlayer(Player *player)
4056 {
4057         v3f pos = findSpawnPos(m_env->getServerMap());
4058         player->setPosition(pos);
4059         player->hp = 20;
4060         SendMovePlayer(player);
4061         SendPlayerHP(player);
4062 }
4063
4064 void Server::UpdateCrafting(u16 peer_id)
4065 {
4066         DSTACK(__FUNCTION_NAME);
4067         
4068         Player* player = m_env->getPlayer(peer_id);
4069         assert(player);
4070
4071         /*
4072                 Calculate crafting stuff
4073         */
4074         if(g_settings->getBool("creative_mode") == false)
4075         {
4076                 InventoryList *clist = player->inventory.getList("craft");
4077                 InventoryList *rlist = player->inventory.getList("craftresult");
4078
4079                 if(rlist && rlist->getUsedSlots() == 0)
4080                         player->craftresult_is_preview = true;
4081
4082                 if(rlist && player->craftresult_is_preview)
4083                 {
4084                         rlist->clearItems();
4085                 }
4086                 if(clist && rlist && player->craftresult_is_preview)
4087                 {
4088                         InventoryItem *items[9];
4089                         for(u16 i=0; i<9; i++)
4090                         {
4091                                 items[i] = clist->getItem(i);
4092                         }
4093                         
4094                         // Get result of crafting grid
4095                         InventoryItem *result = craft_get_result(items);
4096                         if(result)
4097                                 rlist->addItem(result);
4098                 }
4099         
4100         } // if creative_mode == false
4101 }
4102
4103 RemoteClient* Server::getClient(u16 peer_id)
4104 {
4105         DSTACK(__FUNCTION_NAME);
4106         //JMutexAutoLock lock(m_con_mutex);
4107         core::map<u16, RemoteClient*>::Node *n;
4108         n = m_clients.find(peer_id);
4109         // A client should exist for all peers
4110         assert(n != NULL);
4111         return n->getValue();
4112 }
4113
4114 std::wstring Server::getStatusString()
4115 {
4116         std::wostringstream os(std::ios_base::binary);
4117         os<<L"# Server: ";
4118         // Version
4119         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4120         // Uptime
4121         os<<L", uptime="<<m_uptime.get();
4122         // Information about clients
4123         os<<L", clients={";
4124         for(core::map<u16, RemoteClient*>::Iterator
4125                 i = m_clients.getIterator();
4126                 i.atEnd() == false; i++)
4127         {
4128                 // Get client and check that it is valid
4129                 RemoteClient *client = i.getNode()->getValue();
4130                 assert(client->peer_id == i.getNode()->getKey());
4131                 if(client->serialization_version == SER_FMT_VER_INVALID)
4132                         continue;
4133                 // Get player
4134                 Player *player = m_env->getPlayer(client->peer_id);
4135                 // Get name of player
4136                 std::wstring name = L"unknown";
4137                 if(player != NULL)
4138                         name = narrow_to_wide(player->getName());
4139                 // Add name to information string
4140                 os<<name<<L",";
4141         }
4142         os<<L"}";
4143         if(((ServerMap*)(&m_env->getMap()))->isSavingEnabled() == false)
4144                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4145         if(g_settings->get("motd") != "")
4146                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4147         return os.str();
4148 }
4149
4150 // Saves g_settings to configpath given at initialization
4151 void Server::saveConfig()
4152 {
4153         if(m_configpath != "")
4154                 g_settings->updateConfigFile(m_configpath.c_str());
4155 }
4156
4157 void Server::notifyPlayer(const char *name, const std::wstring msg)
4158 {
4159         Player *player = m_env->getPlayer(name);
4160         if(!player)
4161                 return;
4162         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4163 }
4164
4165 void Server::notifyPlayers(const std::wstring msg)
4166 {
4167         BroadcastChatMessage(msg);
4168 }
4169
4170 v3f findSpawnPos(ServerMap &map)
4171 {
4172         //return v3f(50,50,50)*BS;
4173
4174         v3s16 nodepos;
4175         
4176 #if 0
4177         nodepos = v2s16(0,0);
4178         groundheight = 20;
4179 #endif
4180
4181 #if 1
4182         // Try to find a good place a few times
4183         for(s32 i=0; i<1000; i++)
4184         {
4185                 s32 range = 1 + i;
4186                 // We're going to try to throw the player to this position
4187                 v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
4188                                 -range + (myrand()%(range*2)));
4189                 //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
4190                 // Get ground height at point (fallbacks to heightmap function)
4191                 s16 groundheight = map.findGroundLevel(nodepos2d);
4192                 // Don't go underwater
4193                 if(groundheight < WATER_LEVEL)
4194                 {
4195                         //infostream<<"-> Underwater"<<std::endl;
4196                         continue;
4197                 }
4198                 // Don't go to high places
4199                 if(groundheight > WATER_LEVEL + 4)
4200                 {
4201                         //infostream<<"-> Underwater"<<std::endl;
4202                         continue;
4203                 }
4204                 
4205                 nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
4206                 bool is_good = false;
4207                 s32 air_count = 0;
4208                 for(s32 i=0; i<10; i++){
4209                         v3s16 blockpos = getNodeBlockPos(nodepos);
4210                         map.emergeBlock(blockpos, true);
4211                         MapNode n = map.getNodeNoEx(nodepos);
4212                         if(n.getContent() == CONTENT_AIR){
4213                                 air_count++;
4214                                 if(air_count >= 2){
4215                                         is_good = true;
4216                                         nodepos.Y -= 1;
4217                                         break;
4218                                 }
4219                         }
4220                         nodepos.Y++;
4221                 }
4222                 if(is_good){
4223                         // Found a good place
4224                         //infostream<<"Searched through "<<i<<" places."<<std::endl;
4225                         break;
4226                 }
4227         }
4228 #endif
4229         
4230         return intToFloat(nodepos, BS);
4231 }
4232
4233 Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
4234 {
4235         /*
4236                 Try to get an existing player
4237         */
4238         Player *player = m_env->getPlayer(name);
4239         if(player != NULL)
4240         {
4241                 // If player is already connected, cancel
4242                 if(player->peer_id != 0)
4243                 {
4244                         infostream<<"emergePlayer(): Player already connected"<<std::endl;
4245                         return NULL;
4246                 }
4247
4248                 // Got one.
4249                 player->peer_id = peer_id;
4250                 
4251                 // Reset inventory to creative if in creative mode
4252                 if(g_settings->getBool("creative_mode"))
4253                 {
4254                         // Warning: double code below
4255                         // Backup actual inventory
4256                         player->inventory_backup = new Inventory();
4257                         *(player->inventory_backup) = player->inventory;
4258                         // Set creative inventory
4259                         craft_set_creative_inventory(player);
4260                 }
4261
4262                 return player;
4263         }
4264
4265         /*
4266                 If player with the wanted peer_id already exists, cancel.
4267         */
4268         if(m_env->getPlayer(peer_id) != NULL)
4269         {
4270                 infostream<<"emergePlayer(): Player with wrong name but same"
4271                                 " peer_id already exists"<<std::endl;
4272                 return NULL;
4273         }
4274         
4275         /*
4276                 Create a new player
4277         */
4278         {
4279                 player = new ServerRemotePlayer();
4280                 //player->peer_id = c.peer_id;
4281                 //player->peer_id = PEER_ID_INEXISTENT;
4282                 player->peer_id = peer_id;
4283                 player->updateName(name);
4284                 m_authmanager.add(name);
4285                 m_authmanager.setPassword(name, password);
4286                 m_authmanager.setPrivs(name,
4287                                 stringToPrivs(g_settings->get("default_privs")));
4288
4289                 /*
4290                         Set player position
4291                 */
4292                 
4293                 infostream<<"Server: Finding spawn place for player \""
4294                                 <<player->getName()<<"\""<<std::endl;
4295
4296                 v3f pos = findSpawnPos(m_env->getServerMap());
4297
4298                 player->setPosition(pos);
4299
4300                 /*
4301                         Add player to environment
4302                 */
4303
4304                 m_env->addPlayer(player);
4305
4306                 /*
4307                         Add stuff to inventory
4308                 */
4309                 
4310                 if(g_settings->getBool("creative_mode"))
4311                 {
4312                         // Warning: double code above
4313                         // Backup actual inventory
4314                         player->inventory_backup = new Inventory();
4315                         *(player->inventory_backup) = player->inventory;
4316                         // Set creative inventory
4317                         craft_set_creative_inventory(player);
4318                 }
4319                 else if(g_settings->getBool("give_initial_stuff"))
4320                 {
4321                         craft_give_initial_stuff(player);
4322                 }
4323
4324                 return player;
4325                 
4326         } // create new player
4327 }
4328
4329 void Server::handlePeerChange(PeerChange &c)
4330 {
4331         JMutexAutoLock envlock(m_env_mutex);
4332         JMutexAutoLock conlock(m_con_mutex);
4333         
4334         if(c.type == PEER_ADDED)
4335         {
4336                 /*
4337                         Add
4338                 */
4339
4340                 // Error check
4341                 core::map<u16, RemoteClient*>::Node *n;
4342                 n = m_clients.find(c.peer_id);
4343                 // The client shouldn't already exist
4344                 assert(n == NULL);
4345
4346                 // Create client
4347                 RemoteClient *client = new RemoteClient();
4348                 client->peer_id = c.peer_id;
4349                 m_clients.insert(client->peer_id, client);
4350
4351         } // PEER_ADDED
4352         else if(c.type == PEER_REMOVED)
4353         {
4354                 /*
4355                         Delete
4356                 */
4357
4358                 // Error check
4359                 core::map<u16, RemoteClient*>::Node *n;
4360                 n = m_clients.find(c.peer_id);
4361                 // The client should exist
4362                 assert(n != NULL);
4363                 
4364                 /*
4365                         Mark objects to be not known by the client
4366                 */
4367                 RemoteClient *client = n->getValue();
4368                 // Handle objects
4369                 for(core::map<u16, bool>::Iterator
4370                                 i = client->m_known_objects.getIterator();
4371                                 i.atEnd()==false; i++)
4372                 {
4373                         // Get object
4374                         u16 id = i.getNode()->getKey();
4375                         ServerActiveObject* obj = m_env->getActiveObject(id);
4376                         
4377                         if(obj && obj->m_known_by_count > 0)
4378                                 obj->m_known_by_count--;
4379                 }
4380
4381                 // Collect information about leaving in chat
4382                 std::wstring message;
4383                 {
4384                         Player *player = m_env->getPlayer(c.peer_id);
4385                         if(player != NULL)
4386                         {
4387                                 std::wstring name = narrow_to_wide(player->getName());
4388                                 message += L"*** ";
4389                                 message += name;
4390                                 message += L" left game";
4391                                 if(c.timeout)
4392                                         message += L" (timed out)";
4393                         }
4394                 }
4395
4396                 /*// Delete player
4397                 {
4398                         m_env->removePlayer(c.peer_id);
4399                 }*/
4400
4401                 // Set player client disconnected
4402                 {
4403                         Player *player = m_env->getPlayer(c.peer_id);
4404                         if(player != NULL)
4405                                 player->peer_id = 0;
4406                         
4407                         /*
4408                                 Print out action
4409                         */
4410                         if(player != NULL)
4411                         {
4412                                 std::ostringstream os(std::ios_base::binary);
4413                                 for(core::map<u16, RemoteClient*>::Iterator
4414                                         i = m_clients.getIterator();
4415                                         i.atEnd() == false; i++)
4416                                 {
4417                                         RemoteClient *client = i.getNode()->getValue();
4418                                         assert(client->peer_id == i.getNode()->getKey());
4419                                         if(client->serialization_version == SER_FMT_VER_INVALID)
4420                                                 continue;
4421                                         // Get player
4422                                         Player *player = m_env->getPlayer(client->peer_id);
4423                                         if(!player)
4424                                                 continue;
4425                                         // Get name of player
4426                                         os<<player->getName()<<" ";
4427                                 }
4428
4429                                 actionstream<<player->getName()<<" "
4430                                                 <<(c.timeout?"times out.":"leaves game.")
4431                                                 <<" List of players: "
4432                                                 <<os.str()<<std::endl;
4433                         }
4434                 }
4435                 
4436                 // Delete client
4437                 delete m_clients[c.peer_id];
4438                 m_clients.remove(c.peer_id);
4439
4440                 // Send player info to all remaining clients
4441                 SendPlayerInfos();
4442                 
4443                 // Send leave chat message to all remaining clients
4444                 BroadcastChatMessage(message);
4445                 
4446         } // PEER_REMOVED
4447         else
4448         {
4449                 assert(0);
4450         }
4451 }
4452
4453 void Server::handlePeerChanges()
4454 {
4455         while(m_peer_change_queue.size() > 0)
4456         {
4457                 PeerChange c = m_peer_change_queue.pop_front();
4458
4459                 infostream<<"Server: Handling peer change: "
4460                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
4461                                 <<std::endl;
4462
4463                 handlePeerChange(c);
4464         }
4465 }
4466
4467 u64 Server::getPlayerPrivs(Player *player)
4468 {
4469         if(player==NULL)
4470                 return 0;
4471         std::string playername = player->getName();
4472         // Local player gets all privileges regardless of
4473         // what's set on their account.
4474         if(g_settings->get("name") == playername)
4475         {
4476                 return PRIV_ALL;
4477         }
4478         else
4479         {
4480                 return getPlayerAuthPrivs(playername);
4481         }
4482 }
4483
4484 void dedicated_server_loop(Server &server, bool &kill)
4485 {
4486         DSTACK(__FUNCTION_NAME);
4487         
4488         infostream<<DTIME<<std::endl;
4489         infostream<<"========================"<<std::endl;
4490         infostream<<"Running dedicated server"<<std::endl;
4491         infostream<<"========================"<<std::endl;
4492         infostream<<std::endl;
4493
4494         IntervalLimiter m_profiler_interval;
4495
4496         for(;;)
4497         {
4498                 // This is kind of a hack but can be done like this
4499                 // because server.step() is very light
4500                 {
4501                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
4502                         sleep_ms(30);
4503                 }
4504                 server.step(0.030);
4505
4506                 if(server.getShutdownRequested() || kill)
4507                 {
4508                         infostream<<DTIME<<" dedicated_server_loop(): Quitting."<<std::endl;
4509                         break;
4510                 }
4511
4512                 /*
4513                         Profiler
4514                 */
4515                 float profiler_print_interval =
4516                                 g_settings->getFloat("profiler_print_interval");
4517                 if(profiler_print_interval != 0)
4518                 {
4519                         if(m_profiler_interval.step(0.030, profiler_print_interval))
4520                         {
4521                                 infostream<<"Profiler:"<<std::endl;
4522                                 g_profiler->print(infostream);
4523                                 g_profiler->clear();
4524                         }
4525                 }
4526                 
4527                 /*
4528                         Player info
4529                 */
4530                 static int counter = 0;
4531                 counter--;
4532                 if(counter <= 0)
4533                 {
4534                         counter = 10;
4535
4536                         core::list<PlayerInfo> list = server.getPlayerInfo();
4537                         core::list<PlayerInfo>::Iterator i;
4538                         static u32 sum_old = 0;
4539                         u32 sum = PIChecksum(list);
4540                         if(sum != sum_old)
4541                         {
4542                                 infostream<<DTIME<<"Player info:"<<std::endl;
4543                                 for(i=list.begin(); i!=list.end(); i++)
4544                                 {
4545                                         i->PrintLine(&infostream);
4546                                 }
4547                         }
4548                         sum_old = sum;
4549                 }
4550         }
4551 }
4552
4553