Scripting WIP
[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         script_load(m_lua, (porting::path_data + DIR_DELIM + "scripts"
993                         + DIR_DELIM + "default.lua").c_str());
994         
995         // Initialize Environment
996         
997         m_env = new ServerEnvironment(new ServerMap(mapsavedir), m_lua);
998         
999         // Register us to receive map edit events
1000         m_env->getMap().addEventReceiver(this);
1001
1002         // If file exists, load environment metadata
1003         if(fs::PathExists(m_mapsavedir+DIR_DELIM+"env_meta.txt"))
1004         {
1005                 infostream<<"Server: Loading environment metadata"<<std::endl;
1006                 m_env->loadMeta(m_mapsavedir);
1007         }
1008
1009         // Load players
1010         infostream<<"Server: Loading players"<<std::endl;
1011         m_env->deSerializePlayers(m_mapsavedir);
1012 }
1013
1014 Server::~Server()
1015 {
1016         infostream<<"Server::~Server()"<<std::endl;
1017
1018         /*
1019                 Send shutdown message
1020         */
1021         {
1022                 JMutexAutoLock conlock(m_con_mutex);
1023                 
1024                 std::wstring line = L"*** Server shutting down";
1025
1026                 /*
1027                         Send the message to clients
1028                 */
1029                 for(core::map<u16, RemoteClient*>::Iterator
1030                         i = m_clients.getIterator();
1031                         i.atEnd() == false; i++)
1032                 {
1033                         // Get client and check that it is valid
1034                         RemoteClient *client = i.getNode()->getValue();
1035                         assert(client->peer_id == i.getNode()->getKey());
1036                         if(client->serialization_version == SER_FMT_VER_INVALID)
1037                                 continue;
1038
1039                         try{
1040                                 SendChatMessage(client->peer_id, line);
1041                         }
1042                         catch(con::PeerNotFoundException &e)
1043                         {}
1044                 }
1045         }
1046         
1047         {
1048                 JMutexAutoLock envlock(m_env_mutex);
1049
1050                 /*
1051                         Save players
1052                 */
1053                 infostream<<"Server: Saving players"<<std::endl;
1054                 m_env->serializePlayers(m_mapsavedir);
1055
1056                 /*
1057                         Save environment metadata
1058                 */
1059                 infostream<<"Server: Saving environment metadata"<<std::endl;
1060                 m_env->saveMeta(m_mapsavedir);
1061         }
1062                 
1063         /*
1064                 Stop threads
1065         */
1066         stop();
1067         
1068         /*
1069                 Delete clients
1070         */
1071         {
1072                 JMutexAutoLock clientslock(m_con_mutex);
1073
1074                 for(core::map<u16, RemoteClient*>::Iterator
1075                         i = m_clients.getIterator();
1076                         i.atEnd() == false; i++)
1077                 {
1078                         /*// Delete player
1079                         // NOTE: These are removed by env destructor
1080                         {
1081                                 u16 peer_id = i.getNode()->getKey();
1082                                 JMutexAutoLock envlock(m_env_mutex);
1083                                 m_env->removePlayer(peer_id);
1084                         }*/
1085                         
1086                         // Delete client
1087                         delete i.getNode()->getValue();
1088                 }
1089         }
1090
1091         // Delete Environment
1092         delete m_env;
1093         
1094         // Deinitialize scripting
1095         infostream<<"Server: Deinitializing scripting"<<std::endl;
1096         script_deinit(m_lua);
1097 }
1098
1099 void Server::start(unsigned short port)
1100 {
1101         DSTACK(__FUNCTION_NAME);
1102         // Stop thread if already running
1103         m_thread.stop();
1104         
1105         // Initialize connection
1106         m_con.SetTimeoutMs(30);
1107         m_con.Serve(port);
1108
1109         // Start thread
1110         m_thread.setRun(true);
1111         m_thread.Start();
1112         
1113         infostream<<"Server: Started on port "<<port<<std::endl;
1114 }
1115
1116 void Server::stop()
1117 {
1118         DSTACK(__FUNCTION_NAME);
1119         
1120         infostream<<"Server: Stopping and waiting threads"<<std::endl;
1121
1122         // Stop threads (set run=false first so both start stopping)
1123         m_thread.setRun(false);
1124         m_emergethread.setRun(false);
1125         m_thread.stop();
1126         m_emergethread.stop();
1127         
1128         infostream<<"Server: Threads stopped"<<std::endl;
1129 }
1130
1131 void Server::step(float dtime)
1132 {
1133         DSTACK(__FUNCTION_NAME);
1134         // Limit a bit
1135         if(dtime > 2.0)
1136                 dtime = 2.0;
1137         {
1138                 JMutexAutoLock lock(m_step_dtime_mutex);
1139                 m_step_dtime += dtime;
1140         }
1141 }
1142
1143 void Server::AsyncRunStep()
1144 {
1145         DSTACK(__FUNCTION_NAME);
1146         
1147         g_profiler->add("Server::AsyncRunStep (num)", 1);
1148         
1149         float dtime;
1150         {
1151                 JMutexAutoLock lock1(m_step_dtime_mutex);
1152                 dtime = m_step_dtime;
1153         }
1154         
1155         {
1156                 ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
1157                 // Send blocks to clients
1158                 SendBlocks(dtime);
1159         }
1160         
1161         if(dtime < 0.001)
1162                 return;
1163         
1164         g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
1165
1166         //infostream<<"Server steps "<<dtime<<std::endl;
1167         //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
1168         
1169         {
1170                 JMutexAutoLock lock1(m_step_dtime_mutex);
1171                 m_step_dtime -= dtime;
1172         }
1173
1174         /*
1175                 Update uptime
1176         */
1177         {
1178                 m_uptime.set(m_uptime.get() + dtime);
1179         }
1180         
1181         {
1182                 // Process connection's timeouts
1183                 JMutexAutoLock lock2(m_con_mutex);
1184                 ScopeProfiler sp(g_profiler, "Server: connection timeout processing");
1185                 m_con.RunTimeouts(dtime);
1186         }
1187         
1188         {
1189                 // This has to be called so that the client list gets synced
1190                 // with the peer list of the connection
1191                 handlePeerChanges();
1192         }
1193
1194         /*
1195                 Update m_time_of_day and overall game time
1196         */
1197         {
1198                 JMutexAutoLock envlock(m_env_mutex);
1199
1200                 m_time_counter += dtime;
1201                 f32 speed = g_settings->getFloat("time_speed") * 24000./(24.*3600);
1202                 u32 units = (u32)(m_time_counter*speed);
1203                 m_time_counter -= (f32)units / speed;
1204                 
1205                 m_env->setTimeOfDay((m_env->getTimeOfDay() + units) % 24000);
1206                 
1207                 //infostream<<"Server: m_time_of_day = "<<m_time_of_day.get()<<std::endl;
1208
1209                 /*
1210                         Send to clients at constant intervals
1211                 */
1212
1213                 m_time_of_day_send_timer -= dtime;
1214                 if(m_time_of_day_send_timer < 0.0)
1215                 {
1216                         m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
1217
1218                         //JMutexAutoLock envlock(m_env_mutex);
1219                         JMutexAutoLock conlock(m_con_mutex);
1220
1221                         for(core::map<u16, RemoteClient*>::Iterator
1222                                 i = m_clients.getIterator();
1223                                 i.atEnd() == false; i++)
1224                         {
1225                                 RemoteClient *client = i.getNode()->getValue();
1226                                 //Player *player = m_env->getPlayer(client->peer_id);
1227                                 
1228                                 SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
1229                                                 m_env->getTimeOfDay());
1230                                 // Send as reliable
1231                                 m_con.Send(client->peer_id, 0, data, true);
1232                         }
1233                 }
1234         }
1235
1236         {
1237                 JMutexAutoLock lock(m_env_mutex);
1238                 // Step environment
1239                 ScopeProfiler sp(g_profiler, "SEnv step");
1240                 ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
1241                 m_env->step(dtime);
1242         }
1243                 
1244         const float map_timer_and_unload_dtime = 5.15;
1245         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
1246         {
1247                 JMutexAutoLock lock(m_env_mutex);
1248                 // Run Map's timers and unload unused data
1249                 ScopeProfiler sp(g_profiler, "Server: map timer and unload");
1250                 m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
1251                                 g_settings->getFloat("server_unload_unused_data_timeout"));
1252         }
1253         
1254         /*
1255                 Do background stuff
1256         */
1257         
1258         /*
1259                 Transform liquids
1260         */
1261         m_liquid_transform_timer += dtime;
1262         if(m_liquid_transform_timer >= 1.00)
1263         {
1264                 m_liquid_transform_timer -= 1.00;
1265                 
1266                 JMutexAutoLock lock(m_env_mutex);
1267
1268                 ScopeProfiler sp(g_profiler, "Server: liquid transform");
1269
1270                 core::map<v3s16, MapBlock*> modified_blocks;
1271                 m_env->getMap().transformLiquids(modified_blocks);
1272 #if 0           
1273                 /*
1274                         Update lighting
1275                 */
1276                 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1277                 ServerMap &map = ((ServerMap&)m_env->getMap());
1278                 map.updateLighting(modified_blocks, lighting_modified_blocks);
1279                 
1280                 // Add blocks modified by lighting to modified_blocks
1281                 for(core::map<v3s16, MapBlock*>::Iterator
1282                                 i = lighting_modified_blocks.getIterator();
1283                                 i.atEnd() == false; i++)
1284                 {
1285                         MapBlock *block = i.getNode()->getValue();
1286                         modified_blocks.insert(block->getPos(), block);
1287                 }
1288 #endif
1289                 /*
1290                         Set the modified blocks unsent for all the clients
1291                 */
1292                 
1293                 JMutexAutoLock lock2(m_con_mutex);
1294
1295                 for(core::map<u16, RemoteClient*>::Iterator
1296                                 i = m_clients.getIterator();
1297                                 i.atEnd() == false; i++)
1298                 {
1299                         RemoteClient *client = i.getNode()->getValue();
1300                         
1301                         if(modified_blocks.size() > 0)
1302                         {
1303                                 // Remove block from sent history
1304                                 client->SetBlocksNotSent(modified_blocks);
1305                         }
1306                 }
1307         }
1308
1309         // Periodically print some info
1310         {
1311                 float &counter = m_print_info_timer;
1312                 counter += dtime;
1313                 if(counter >= 30.0)
1314                 {
1315                         counter = 0.0;
1316
1317                         JMutexAutoLock lock2(m_con_mutex);
1318                         
1319                         if(m_clients.size() != 0)
1320                                 infostream<<"Players:"<<std::endl;
1321                         for(core::map<u16, RemoteClient*>::Iterator
1322                                 i = m_clients.getIterator();
1323                                 i.atEnd() == false; i++)
1324                         {
1325                                 //u16 peer_id = i.getNode()->getKey();
1326                                 RemoteClient *client = i.getNode()->getValue();
1327                                 Player *player = m_env->getPlayer(client->peer_id);
1328                                 if(player==NULL)
1329                                         continue;
1330                                 infostream<<"* "<<player->getName()<<"\t";
1331                                 client->PrintInfo(infostream);
1332                         }
1333                 }
1334         }
1335
1336         //if(g_settings->getBool("enable_experimental"))
1337         {
1338
1339         /*
1340                 Check added and deleted active objects
1341         */
1342         {
1343                 //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
1344                 JMutexAutoLock envlock(m_env_mutex);
1345                 JMutexAutoLock conlock(m_con_mutex);
1346
1347                 ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
1348
1349                 // Radius inside which objects are active
1350                 s16 radius = g_settings->getS16("active_object_send_range_blocks");
1351                 radius *= MAP_BLOCKSIZE;
1352
1353                 for(core::map<u16, RemoteClient*>::Iterator
1354                         i = m_clients.getIterator();
1355                         i.atEnd() == false; i++)
1356                 {
1357                         RemoteClient *client = i.getNode()->getValue();
1358                         Player *player = m_env->getPlayer(client->peer_id);
1359                         if(player==NULL)
1360                         {
1361                                 // This can happen if the client timeouts somehow
1362                                 /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
1363                                                 <<client->peer_id
1364                                                 <<" has no associated player"<<std::endl;*/
1365                                 continue;
1366                         }
1367                         v3s16 pos = floatToInt(player->getPosition(), BS);
1368
1369                         core::map<u16, bool> removed_objects;
1370                         core::map<u16, bool> added_objects;
1371                         m_env->getRemovedActiveObjects(pos, radius,
1372                                         client->m_known_objects, removed_objects);
1373                         m_env->getAddedActiveObjects(pos, radius,
1374                                         client->m_known_objects, added_objects);
1375                         
1376                         // Ignore if nothing happened
1377                         if(removed_objects.size() == 0 && added_objects.size() == 0)
1378                         {
1379                                 //infostream<<"active objects: none changed"<<std::endl;
1380                                 continue;
1381                         }
1382                         
1383                         std::string data_buffer;
1384
1385                         char buf[4];
1386                         
1387                         // Handle removed objects
1388                         writeU16((u8*)buf, removed_objects.size());
1389                         data_buffer.append(buf, 2);
1390                         for(core::map<u16, bool>::Iterator
1391                                         i = removed_objects.getIterator();
1392                                         i.atEnd()==false; i++)
1393                         {
1394                                 // Get object
1395                                 u16 id = i.getNode()->getKey();
1396                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1397
1398                                 // Add to data buffer for sending
1399                                 writeU16((u8*)buf, i.getNode()->getKey());
1400                                 data_buffer.append(buf, 2);
1401                                 
1402                                 // Remove from known objects
1403                                 client->m_known_objects.remove(i.getNode()->getKey());
1404
1405                                 if(obj && obj->m_known_by_count > 0)
1406                                         obj->m_known_by_count--;
1407                         }
1408
1409                         // Handle added objects
1410                         writeU16((u8*)buf, added_objects.size());
1411                         data_buffer.append(buf, 2);
1412                         for(core::map<u16, bool>::Iterator
1413                                         i = added_objects.getIterator();
1414                                         i.atEnd()==false; i++)
1415                         {
1416                                 // Get object
1417                                 u16 id = i.getNode()->getKey();
1418                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1419                                 
1420                                 // Get object type
1421                                 u8 type = ACTIVEOBJECT_TYPE_INVALID;
1422                                 if(obj == NULL)
1423                                         infostream<<"WARNING: "<<__FUNCTION_NAME
1424                                                         <<": NULL object"<<std::endl;
1425                                 else
1426                                         type = obj->getType();
1427
1428                                 // Add to data buffer for sending
1429                                 writeU16((u8*)buf, id);
1430                                 data_buffer.append(buf, 2);
1431                                 writeU8((u8*)buf, type);
1432                                 data_buffer.append(buf, 1);
1433                                 
1434                                 if(obj)
1435                                         data_buffer.append(serializeLongString(
1436                                                         obj->getClientInitializationData()));
1437                                 else
1438                                         data_buffer.append(serializeLongString(""));
1439
1440                                 // Add to known objects
1441                                 client->m_known_objects.insert(i.getNode()->getKey(), false);
1442
1443                                 if(obj)
1444                                         obj->m_known_by_count++;
1445                         }
1446
1447                         // Send packet
1448                         SharedBuffer<u8> reply(2 + data_buffer.size());
1449                         writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD);
1450                         memcpy((char*)&reply[2], data_buffer.c_str(),
1451                                         data_buffer.size());
1452                         // Send as reliable
1453                         m_con.Send(client->peer_id, 0, reply, true);
1454
1455                         infostream<<"Server: Sent object remove/add: "
1456                                         <<removed_objects.size()<<" removed, "
1457                                         <<added_objects.size()<<" added, "
1458                                         <<"packet size is "<<reply.getSize()<<std::endl;
1459                 }
1460
1461 #if 0
1462                 /*
1463                         Collect a list of all the objects known by the clients
1464                         and report it back to the environment.
1465                 */
1466
1467                 core::map<u16, bool> all_known_objects;
1468
1469                 for(core::map<u16, RemoteClient*>::Iterator
1470                         i = m_clients.getIterator();
1471                         i.atEnd() == false; i++)
1472                 {
1473                         RemoteClient *client = i.getNode()->getValue();
1474                         // Go through all known objects of client
1475                         for(core::map<u16, bool>::Iterator
1476                                         i = client->m_known_objects.getIterator();
1477                                         i.atEnd()==false; i++)
1478                         {
1479                                 u16 id = i.getNode()->getKey();
1480                                 all_known_objects[id] = true;
1481                         }
1482                 }
1483                 
1484                 m_env->setKnownActiveObjects(whatever);
1485 #endif
1486
1487         }
1488
1489         /*
1490                 Send object messages
1491         */
1492         {
1493                 JMutexAutoLock envlock(m_env_mutex);
1494                 JMutexAutoLock conlock(m_con_mutex);
1495
1496                 //ScopeProfiler sp(g_profiler, "Server: sending object messages");
1497
1498                 // Key = object id
1499                 // Value = data sent by object
1500                 core::map<u16, core::list<ActiveObjectMessage>* > buffered_messages;
1501
1502                 // Get active object messages from environment
1503                 for(;;)
1504                 {
1505                         ActiveObjectMessage aom = m_env->getActiveObjectMessage();
1506                         if(aom.id == 0)
1507                                 break;
1508                         
1509                         core::list<ActiveObjectMessage>* message_list = NULL;
1510                         core::map<u16, core::list<ActiveObjectMessage>* >::Node *n;
1511                         n = buffered_messages.find(aom.id);
1512                         if(n == NULL)
1513                         {
1514                                 message_list = new core::list<ActiveObjectMessage>;
1515                                 buffered_messages.insert(aom.id, message_list);
1516                         }
1517                         else
1518                         {
1519                                 message_list = n->getValue();
1520                         }
1521                         message_list->push_back(aom);
1522                 }
1523                 
1524                 // Route data to every client
1525                 for(core::map<u16, RemoteClient*>::Iterator
1526                         i = m_clients.getIterator();
1527                         i.atEnd()==false; i++)
1528                 {
1529                         RemoteClient *client = i.getNode()->getValue();
1530                         std::string reliable_data;
1531                         std::string unreliable_data;
1532                         // Go through all objects in message buffer
1533                         for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1534                                         j = buffered_messages.getIterator();
1535                                         j.atEnd()==false; j++)
1536                         {
1537                                 // If object is not known by client, skip it
1538                                 u16 id = j.getNode()->getKey();
1539                                 if(client->m_known_objects.find(id) == NULL)
1540                                         continue;
1541                                 // Get message list of object
1542                                 core::list<ActiveObjectMessage>* list = j.getNode()->getValue();
1543                                 // Go through every message
1544                                 for(core::list<ActiveObjectMessage>::Iterator
1545                                                 k = list->begin(); k != list->end(); k++)
1546                                 {
1547                                         // Compose the full new data with header
1548                                         ActiveObjectMessage aom = *k;
1549                                         std::string new_data;
1550                                         // Add object id
1551                                         char buf[2];
1552                                         writeU16((u8*)&buf[0], aom.id);
1553                                         new_data.append(buf, 2);
1554                                         // Add data
1555                                         new_data += serializeString(aom.datastring);
1556                                         // Add data to buffer
1557                                         if(aom.reliable)
1558                                                 reliable_data += new_data;
1559                                         else
1560                                                 unreliable_data += new_data;
1561                                 }
1562                         }
1563                         /*
1564                                 reliable_data and unreliable_data are now ready.
1565                                 Send them.
1566                         */
1567                         if(reliable_data.size() > 0)
1568                         {
1569                                 SharedBuffer<u8> reply(2 + reliable_data.size());
1570                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1571                                 memcpy((char*)&reply[2], reliable_data.c_str(),
1572                                                 reliable_data.size());
1573                                 // Send as reliable
1574                                 m_con.Send(client->peer_id, 0, reply, true);
1575                         }
1576                         if(unreliable_data.size() > 0)
1577                         {
1578                                 SharedBuffer<u8> reply(2 + unreliable_data.size());
1579                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1580                                 memcpy((char*)&reply[2], unreliable_data.c_str(),
1581                                                 unreliable_data.size());
1582                                 // Send as unreliable
1583                                 m_con.Send(client->peer_id, 0, reply, false);
1584                         }
1585
1586                         /*if(reliable_data.size() > 0 || unreliable_data.size() > 0)
1587                         {
1588                                 infostream<<"Server: Size of object message data: "
1589                                                 <<"reliable: "<<reliable_data.size()
1590                                                 <<", unreliable: "<<unreliable_data.size()
1591                                                 <<std::endl;
1592                         }*/
1593                 }
1594
1595                 // Clear buffered_messages
1596                 for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1597                                 i = buffered_messages.getIterator();
1598                                 i.atEnd()==false; i++)
1599                 {
1600                         delete i.getNode()->getValue();
1601                 }
1602         }
1603
1604         } // enable_experimental
1605
1606         /*
1607                 Send queued-for-sending map edit events.
1608         */
1609         {
1610                 // Don't send too many at a time
1611                 //u32 count = 0;
1612
1613                 // Single change sending is disabled if queue size is not small
1614                 bool disable_single_change_sending = false;
1615                 if(m_unsent_map_edit_queue.size() >= 4)
1616                         disable_single_change_sending = true;
1617
1618                 bool got_any_events = false;
1619
1620                 // We'll log the amount of each
1621                 Profiler prof;
1622
1623                 while(m_unsent_map_edit_queue.size() != 0)
1624                 {
1625                         got_any_events = true;
1626
1627                         MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
1628                         
1629                         // Players far away from the change are stored here.
1630                         // Instead of sending the changes, MapBlocks are set not sent
1631                         // for them.
1632                         core::list<u16> far_players;
1633
1634                         if(event->type == MEET_ADDNODE)
1635                         {
1636                                 //infostream<<"Server: MEET_ADDNODE"<<std::endl;
1637                                 prof.add("MEET_ADDNODE", 1);
1638                                 if(disable_single_change_sending)
1639                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1640                                                         &far_players, 5);
1641                                 else
1642                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1643                                                         &far_players, 30);
1644                         }
1645                         else if(event->type == MEET_REMOVENODE)
1646                         {
1647                                 //infostream<<"Server: MEET_REMOVENODE"<<std::endl;
1648                                 prof.add("MEET_REMOVENODE", 1);
1649                                 if(disable_single_change_sending)
1650                                         sendRemoveNode(event->p, event->already_known_by_peer,
1651                                                         &far_players, 5);
1652                                 else
1653                                         sendRemoveNode(event->p, event->already_known_by_peer,
1654                                                         &far_players, 30);
1655                         }
1656                         else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED)
1657                         {
1658                                 infostream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<<std::endl;
1659                                 prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
1660                                 setBlockNotSent(event->p);
1661                         }
1662                         else if(event->type == MEET_OTHER)
1663                         {
1664                                 infostream<<"Server: MEET_OTHER"<<std::endl;
1665                                 prof.add("MEET_OTHER", 1);
1666                                 for(core::map<v3s16, bool>::Iterator
1667                                                 i = event->modified_blocks.getIterator();
1668                                                 i.atEnd()==false; i++)
1669                                 {
1670                                         v3s16 p = i.getNode()->getKey();
1671                                         setBlockNotSent(p);
1672                                 }
1673                         }
1674                         else
1675                         {
1676                                 prof.add("unknown", 1);
1677                                 infostream<<"WARNING: Server: Unknown MapEditEvent "
1678                                                 <<((u32)event->type)<<std::endl;
1679                         }
1680                         
1681                         /*
1682                                 Set blocks not sent to far players
1683                         */
1684                         if(far_players.size() > 0)
1685                         {
1686                                 // Convert list format to that wanted by SetBlocksNotSent
1687                                 core::map<v3s16, MapBlock*> modified_blocks2;
1688                                 for(core::map<v3s16, bool>::Iterator
1689                                                 i = event->modified_blocks.getIterator();
1690                                                 i.atEnd()==false; i++)
1691                                 {
1692                                         v3s16 p = i.getNode()->getKey();
1693                                         modified_blocks2.insert(p,
1694                                                         m_env->getMap().getBlockNoCreateNoEx(p));
1695                                 }
1696                                 // Set blocks not sent
1697                                 for(core::list<u16>::Iterator
1698                                                 i = far_players.begin();
1699                                                 i != far_players.end(); i++)
1700                                 {
1701                                         u16 peer_id = *i;
1702                                         RemoteClient *client = getClient(peer_id);
1703                                         if(client==NULL)
1704                                                 continue;
1705                                         client->SetBlocksNotSent(modified_blocks2);
1706                                 }
1707                         }
1708
1709                         delete event;
1710
1711                         /*// Don't send too many at a time
1712                         count++;
1713                         if(count >= 1 && m_unsent_map_edit_queue.size() < 100)
1714                                 break;*/
1715                 }
1716
1717                 if(got_any_events)
1718                 {
1719                         infostream<<"Server: MapEditEvents:"<<std::endl;
1720                         prof.print(infostream);
1721                 }
1722                 
1723         }
1724
1725         /*
1726                 Send object positions
1727         */
1728         {
1729                 float &counter = m_objectdata_timer;
1730                 counter += dtime;
1731                 if(counter >= g_settings->getFloat("objectdata_interval"))
1732                 {
1733                         JMutexAutoLock lock1(m_env_mutex);
1734                         JMutexAutoLock lock2(m_con_mutex);
1735
1736                         //ScopeProfiler sp(g_profiler, "Server: sending player positions");
1737
1738                         SendObjectData(counter);
1739
1740                         counter = 0.0;
1741                 }
1742         }
1743         
1744         /*
1745                 Trigger emergethread (it somehow gets to a non-triggered but
1746                 bysy state sometimes)
1747         */
1748         {
1749                 float &counter = m_emergethread_trigger_timer;
1750                 counter += dtime;
1751                 if(counter >= 2.0)
1752                 {
1753                         counter = 0.0;
1754                         
1755                         m_emergethread.trigger();
1756                 }
1757         }
1758
1759         // Save map, players and auth stuff
1760         {
1761                 float &counter = m_savemap_timer;
1762                 counter += dtime;
1763                 if(counter >= g_settings->getFloat("server_map_save_interval"))
1764                 {
1765                         counter = 0.0;
1766
1767                         ScopeProfiler sp(g_profiler, "Server: saving stuff");
1768
1769                         // Auth stuff
1770                         if(m_authmanager.isModified())
1771                                 m_authmanager.save();
1772
1773                         //Bann stuff
1774                         if(m_banmanager.isModified())
1775                                 m_banmanager.save();
1776                         
1777                         // Map
1778                         JMutexAutoLock lock(m_env_mutex);
1779
1780                         /*// Unload unused data (delete from memory)
1781                         m_env->getMap().unloadUnusedData(
1782                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1783                                         */
1784                         /*u32 deleted_count = m_env->getMap().unloadUnusedData(
1785                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1786                                         */
1787
1788                         // Save only changed parts
1789                         m_env->getMap().save(true);
1790
1791                         /*if(deleted_count > 0)
1792                         {
1793                                 infostream<<"Server: Unloaded "<<deleted_count
1794                                                 <<" blocks from memory"<<std::endl;
1795                         }*/
1796
1797                         // Save players
1798                         m_env->serializePlayers(m_mapsavedir);
1799                         
1800                         // Save environment metadata
1801                         m_env->saveMeta(m_mapsavedir);
1802                 }
1803         }
1804 }
1805
1806 void Server::Receive()
1807 {
1808         DSTACK(__FUNCTION_NAME);
1809         SharedBuffer<u8> data;
1810         u16 peer_id;
1811         u32 datasize;
1812         try{
1813                 {
1814                         JMutexAutoLock conlock(m_con_mutex);
1815                         datasize = m_con.Receive(peer_id, data);
1816                 }
1817
1818                 // This has to be called so that the client list gets synced
1819                 // with the peer list of the connection
1820                 handlePeerChanges();
1821
1822                 ProcessData(*data, datasize, peer_id);
1823         }
1824         catch(con::InvalidIncomingDataException &e)
1825         {
1826                 infostream<<"Server::Receive(): "
1827                                 "InvalidIncomingDataException: what()="
1828                                 <<e.what()<<std::endl;
1829         }
1830         catch(con::PeerNotFoundException &e)
1831         {
1832                 //NOTE: This is not needed anymore
1833                 
1834                 // The peer has been disconnected.
1835                 // Find the associated player and remove it.
1836
1837                 /*JMutexAutoLock envlock(m_env_mutex);
1838
1839                 infostream<<"ServerThread: peer_id="<<peer_id
1840                                 <<" has apparently closed connection. "
1841                                 <<"Removing player."<<std::endl;
1842
1843                 m_env->removePlayer(peer_id);*/
1844         }
1845 }
1846
1847 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1848 {
1849         DSTACK(__FUNCTION_NAME);
1850         // Environment is locked first.
1851         JMutexAutoLock envlock(m_env_mutex);
1852         JMutexAutoLock conlock(m_con_mutex);
1853         
1854         try{
1855                 Address address = m_con.GetPeerAddress(peer_id);
1856
1857                 // drop player if is ip is banned
1858                 if(m_banmanager.isIpBanned(address.serializeString())){
1859                         SendAccessDenied(m_con, peer_id,
1860                                         L"Your ip is banned. Banned name was "
1861                                         +narrow_to_wide(m_banmanager.getBanName(
1862                                                 address.serializeString())));
1863                         m_con.DeletePeer(peer_id);
1864                         return;
1865                 }
1866         }
1867         catch(con::PeerNotFoundException &e)
1868         {
1869                 infostream<<"Server::ProcessData(): Cancelling: peer "
1870                                 <<peer_id<<" not found"<<std::endl;
1871                 return;
1872         }
1873
1874         u8 peer_ser_ver = getClient(peer_id)->serialization_version;
1875
1876         try
1877         {
1878
1879         if(datasize < 2)
1880                 return;
1881
1882         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1883         
1884         if(command == TOSERVER_INIT)
1885         {
1886                 // [0] u16 TOSERVER_INIT
1887                 // [2] u8 SER_FMT_VER_HIGHEST
1888                 // [3] u8[20] player_name
1889                 // [23] u8[28] password <--- can be sent without this, from old versions
1890
1891                 if(datasize < 2+1+PLAYERNAME_SIZE)
1892                         return;
1893
1894                 infostream<<"Server: Got TOSERVER_INIT from "
1895                                 <<peer_id<<std::endl;
1896
1897                 // First byte after command is maximum supported
1898                 // serialization version
1899                 u8 client_max = data[2];
1900                 u8 our_max = SER_FMT_VER_HIGHEST;
1901                 // Use the highest version supported by both
1902                 u8 deployed = core::min_(client_max, our_max);
1903                 // If it's lower than the lowest supported, give up.
1904                 if(deployed < SER_FMT_VER_LOWEST)
1905                         deployed = SER_FMT_VER_INVALID;
1906
1907                 //peer->serialization_version = deployed;
1908                 getClient(peer_id)->pending_serialization_version = deployed;
1909                 
1910                 if(deployed == SER_FMT_VER_INVALID)
1911                 {
1912                         infostream<<"Server: Cannot negotiate "
1913                                         "serialization version with peer "
1914                                         <<peer_id<<std::endl;
1915                         SendAccessDenied(m_con, peer_id,
1916                                         L"Your client is too old (map format)");
1917                         return;
1918                 }
1919                 
1920                 /*
1921                         Read and check network protocol version
1922                 */
1923
1924                 u16 net_proto_version = 0;
1925                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
1926                 {
1927                         net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
1928                 }
1929
1930                 getClient(peer_id)->net_proto_version = net_proto_version;
1931
1932                 if(net_proto_version == 0)
1933                 {
1934                         SendAccessDenied(m_con, peer_id,
1935                                         L"Your client is too old. Please upgrade.");
1936                         return;
1937                 }
1938                 
1939                 /* Uhh... this should actually be a warning but let's do it like this */
1940                 if(g_settings->getBool("strict_protocol_version_checking"))
1941                 {
1942                         if(net_proto_version < PROTOCOL_VERSION)
1943                         {
1944                                 SendAccessDenied(m_con, peer_id,
1945                                                 L"Your client is too old. Please upgrade.");
1946                                 return;
1947                         }
1948                 }
1949
1950                 /*
1951                         Set up player
1952                 */
1953                 
1954                 // Get player name
1955                 char playername[PLAYERNAME_SIZE];
1956                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
1957                 {
1958                         playername[i] = data[3+i];
1959                 }
1960                 playername[PLAYERNAME_SIZE-1] = 0;
1961                 
1962                 if(playername[0]=='\0')
1963                 {
1964                         infostream<<"Server: Player has empty name"<<std::endl;
1965                         SendAccessDenied(m_con, peer_id,
1966                                         L"Empty name");
1967                         return;
1968                 }
1969
1970                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1971                 {
1972                         infostream<<"Server: Player has invalid name"<<std::endl;
1973                         SendAccessDenied(m_con, peer_id,
1974                                         L"Name contains unallowed characters");
1975                         return;
1976                 }
1977
1978                 // Get password
1979                 char password[PASSWORD_SIZE];
1980                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
1981                 {
1982                         // old version - assume blank password
1983                         password[0] = 0;
1984                 }
1985                 else
1986                 {
1987                                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
1988                                 {
1989                                         password[i] = data[23+i];
1990                                 }
1991                                 password[PASSWORD_SIZE-1] = 0;
1992                 }
1993                 
1994                 std::string checkpwd;
1995                 if(m_authmanager.exists(playername))
1996                 {
1997                         checkpwd = m_authmanager.getPassword(playername);
1998                 }
1999                 else
2000                 {
2001                         checkpwd = g_settings->get("default_password");
2002                 }
2003                 
2004                 /*infostream<<"Server: Client gave password '"<<password
2005                                 <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
2006                 
2007                 if(password != checkpwd && m_authmanager.exists(playername))
2008                 {
2009                         infostream<<"Server: peer_id="<<peer_id
2010                                         <<": supplied invalid password for "
2011                                         <<playername<<std::endl;
2012                         SendAccessDenied(m_con, peer_id, L"Invalid password");
2013                         return;
2014                 }
2015                 
2016                 // Add player to auth manager
2017                 if(m_authmanager.exists(playername) == false)
2018                 {
2019                         infostream<<"Server: adding player "<<playername
2020                                         <<" to auth manager"<<std::endl;
2021                         m_authmanager.add(playername);
2022                         m_authmanager.setPassword(playername, checkpwd);
2023                         m_authmanager.setPrivs(playername,
2024                                         stringToPrivs(g_settings->get("default_privs")));
2025                         m_authmanager.save();
2026                 }
2027                 
2028                 // Enforce user limit.
2029                 // Don't enforce for users that have some admin right
2030                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2031                                 (m_authmanager.getPrivs(playername)
2032                                         & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
2033                                 playername != g_settings->get("name"))
2034                 {
2035                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2036                         return;
2037                 }
2038
2039                 // Get player
2040                 Player *player = emergePlayer(playername, password, peer_id);
2041
2042                 // If failed, cancel
2043                 if(player == NULL)
2044                 {
2045                         infostream<<"Server: peer_id="<<peer_id
2046                                         <<": failed to emerge player"<<std::endl;
2047                         return;
2048                 }
2049
2050                 /*
2051                         Answer with a TOCLIENT_INIT
2052                 */
2053                 {
2054                         SharedBuffer<u8> reply(2+1+6+8);
2055                         writeU16(&reply[0], TOCLIENT_INIT);
2056                         writeU8(&reply[2], deployed);
2057                         writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
2058                         writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
2059                         
2060                         // Send as reliable
2061                         m_con.Send(peer_id, 0, reply, true);
2062                 }
2063
2064                 /*
2065                         Send complete position information
2066                 */
2067                 SendMovePlayer(player);
2068
2069                 return;
2070         }
2071
2072         if(command == TOSERVER_INIT2)
2073         {
2074                 infostream<<"Server: Got TOSERVER_INIT2 from "
2075                                 <<peer_id<<std::endl;
2076
2077
2078                 getClient(peer_id)->serialization_version
2079                                 = getClient(peer_id)->pending_serialization_version;
2080
2081                 /*
2082                         Send some initialization data
2083                 */
2084                 
2085                 // Send player info to all players
2086                 SendPlayerInfos();
2087
2088                 // Send inventory to player
2089                 UpdateCrafting(peer_id);
2090                 SendInventory(peer_id);
2091
2092                 // Send player items to all players
2093                 SendPlayerItems();
2094
2095                 Player *player = m_env->getPlayer(peer_id);
2096
2097                 // Send HP
2098                 SendPlayerHP(player);
2099                 
2100                 // Send time of day
2101                 {
2102                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2103                                         m_env->getTimeOfDay());
2104                         m_con.Send(peer_id, 0, data, true);
2105                 }
2106                 
2107                 // Send information about server to player in chat
2108                 SendChatMessage(peer_id, getStatusString());
2109                 
2110                 // Send information about joining in chat
2111                 {
2112                         std::wstring name = L"unknown";
2113                         Player *player = m_env->getPlayer(peer_id);
2114                         if(player != NULL)
2115                                 name = narrow_to_wide(player->getName());
2116                         
2117                         std::wstring message;
2118                         message += L"*** ";
2119                         message += name;
2120                         message += L" joined game";
2121                         BroadcastChatMessage(message);
2122                 }
2123                 
2124                 // Warnings about protocol version can be issued here
2125                 if(getClient(peer_id)->net_proto_version < PROTOCOL_VERSION)
2126                 {
2127                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
2128                 }
2129
2130                 /*
2131                         Check HP, respawn if necessary
2132                 */
2133                 HandlePlayerHP(player, 0);
2134
2135                 /*
2136                         Print out action
2137                 */
2138                 {
2139                         std::ostringstream os(std::ios_base::binary);
2140                         for(core::map<u16, RemoteClient*>::Iterator
2141                                 i = m_clients.getIterator();
2142                                 i.atEnd() == false; i++)
2143                         {
2144                                 RemoteClient *client = i.getNode()->getValue();
2145                                 assert(client->peer_id == i.getNode()->getKey());
2146                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2147                                         continue;
2148                                 // Get player
2149                                 Player *player = m_env->getPlayer(client->peer_id);
2150                                 if(!player)
2151                                         continue;
2152                                 // Get name of player
2153                                 os<<player->getName()<<" ";
2154                         }
2155
2156                         actionstream<<player->getName()<<" joins game. List of players: "
2157                                         <<os.str()<<std::endl;
2158                 }
2159
2160                 return;
2161         }
2162
2163         if(peer_ser_ver == SER_FMT_VER_INVALID)
2164         {
2165                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2166                                 " serialization format invalid or not initialized."
2167                                 " Skipping incoming command="<<command<<std::endl;
2168                 return;
2169         }
2170         
2171         Player *player = m_env->getPlayer(peer_id);
2172
2173         if(player == NULL){
2174                 infostream<<"Server::ProcessData(): Cancelling: "
2175                                 "No player for peer_id="<<peer_id
2176                                 <<std::endl;
2177                 return;
2178         }
2179         if(command == TOSERVER_PLAYERPOS)
2180         {
2181                 if(datasize < 2+12+12+4+4)
2182                         return;
2183         
2184                 u32 start = 0;
2185                 v3s32 ps = readV3S32(&data[start+2]);
2186                 v3s32 ss = readV3S32(&data[start+2+12]);
2187                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2188                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2189                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2190                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2191                 pitch = wrapDegrees(pitch);
2192                 yaw = wrapDegrees(yaw);
2193
2194                 player->setPosition(position);
2195                 player->setSpeed(speed);
2196                 player->setPitch(pitch);
2197                 player->setYaw(yaw);
2198                 
2199                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2200                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2201                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2202         }
2203         else if(command == TOSERVER_GOTBLOCKS)
2204         {
2205                 if(datasize < 2+1)
2206                         return;
2207                 
2208                 /*
2209                         [0] u16 command
2210                         [2] u8 count
2211                         [3] v3s16 pos_0
2212                         [3+6] v3s16 pos_1
2213                         ...
2214                 */
2215
2216                 u16 count = data[2];
2217                 for(u16 i=0; i<count; i++)
2218                 {
2219                         if((s16)datasize < 2+1+(i+1)*6)
2220                                 throw con::InvalidIncomingDataException
2221                                         ("GOTBLOCKS length is too short");
2222                         v3s16 p = readV3S16(&data[2+1+i*6]);
2223                         /*infostream<<"Server: GOTBLOCKS ("
2224                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2225                         RemoteClient *client = getClient(peer_id);
2226                         client->GotBlock(p);
2227                 }
2228         }
2229         else if(command == TOSERVER_DELETEDBLOCKS)
2230         {
2231                 if(datasize < 2+1)
2232                         return;
2233                 
2234                 /*
2235                         [0] u16 command
2236                         [2] u8 count
2237                         [3] v3s16 pos_0
2238                         [3+6] v3s16 pos_1
2239                         ...
2240                 */
2241
2242                 u16 count = data[2];
2243                 for(u16 i=0; i<count; i++)
2244                 {
2245                         if((s16)datasize < 2+1+(i+1)*6)
2246                                 throw con::InvalidIncomingDataException
2247                                         ("DELETEDBLOCKS length is too short");
2248                         v3s16 p = readV3S16(&data[2+1+i*6]);
2249                         /*infostream<<"Server: DELETEDBLOCKS ("
2250                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2251                         RemoteClient *client = getClient(peer_id);
2252                         client->SetBlockNotSent(p);
2253                 }
2254         }
2255         else if(command == TOSERVER_CLICK_OBJECT)
2256         {
2257                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2258                 return;
2259         }
2260         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2261         {
2262                 if(datasize < 7)
2263                         return;
2264
2265                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2266                         return;
2267
2268                 /*
2269                         length: 7
2270                         [0] u16 command
2271                         [2] u8 button (0=left, 1=right)
2272                         [3] u16 id
2273                         [5] u16 item
2274                 */
2275                 u8 button = readU8(&data[2]);
2276                 u16 id = readS16(&data[3]);
2277                 u16 item_i = readU16(&data[5]);
2278         
2279                 ServerActiveObject *obj = m_env->getActiveObject(id);
2280
2281                 if(obj == NULL)
2282                 {
2283                         infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
2284                                         <<std::endl;
2285                         return;
2286                 }
2287
2288                 // Skip if object has been removed
2289                 if(obj->m_removed)
2290                         return;
2291                 
2292                 //TODO: Check that object is reasonably close
2293                 
2294                 // Left click, pick object up (usually)
2295                 if(button == 0)
2296                 {
2297                         /*
2298                                 Try creating inventory item
2299                         */
2300                         InventoryItem *item = obj->createPickedUpItem();
2301                         
2302                         if(item)
2303                         {
2304                                 InventoryList *ilist = player->inventory.getList("main");
2305                                 if(ilist != NULL)
2306                                 {
2307                                         actionstream<<player->getName()<<" picked up "
2308                                                         <<item->getName()<<std::endl;
2309                                         if(g_settings->getBool("creative_mode") == false)
2310                                         {
2311                                                 // Skip if inventory has no free space
2312                                                 if(ilist->roomForItem(item) == false)
2313                                                 {
2314                                                         infostream<<"Player inventory has no free space"<<std::endl;
2315                                                         return;
2316                                                 }
2317
2318                                                 // Add to inventory and send inventory
2319                                                 ilist->addItem(item);
2320                                                 UpdateCrafting(player->peer_id);
2321                                                 SendInventory(player->peer_id);
2322                                         }
2323
2324                                         // Remove object from environment
2325                                         obj->m_removed = true;
2326                                 }
2327                         }
2328                         else
2329                         {
2330                                 /*
2331                                         Item cannot be picked up. Punch it instead.
2332                                 */
2333
2334                                 actionstream<<player->getName()<<" punches object "
2335                                                 <<obj->getId()<<std::endl;
2336
2337                                 ToolItem *titem = NULL;
2338                                 std::string toolname = "";
2339
2340                                 InventoryList *mlist = player->inventory.getList("main");
2341                                 if(mlist != NULL)
2342                                 {
2343                                         InventoryItem *item = mlist->getItem(item_i);
2344                                         if(item && (std::string)item->getName() == "ToolItem")
2345                                         {
2346                                                 titem = (ToolItem*)item;
2347                                                 toolname = titem->getToolName();
2348                                         }
2349                                 }
2350
2351                                 v3f playerpos = player->getPosition();
2352                                 v3f objpos = obj->getBasePosition();
2353                                 v3f dir = (objpos - playerpos).normalize();
2354                                 
2355                                 u16 wear = obj->punch(toolname, dir, player->getName());
2356                                 
2357                                 if(titem)
2358                                 {
2359                                         bool weared_out = titem->addWear(wear);
2360                                         if(weared_out)
2361                                                 mlist->deleteItem(item_i);
2362                                         SendInventory(player->peer_id);
2363                                 }
2364                         }
2365                 }
2366                 // Right click, do something with object
2367                 if(button == 1)
2368                 {
2369                         actionstream<<player->getName()<<" right clicks object "
2370                                         <<obj->getId()<<std::endl;
2371
2372                         // Track hp changes super-crappily
2373                         u16 oldhp = player->hp;
2374                         
2375                         // Do stuff
2376                         obj->rightClick(player);
2377                         
2378                         // Send back stuff
2379                         if(player->hp != oldhp)
2380                         {
2381                                 SendPlayerHP(player);
2382                         }
2383                 }
2384         }
2385         else if(command == TOSERVER_GROUND_ACTION)
2386         {
2387                 if(datasize < 17)
2388                         return;
2389                 /*
2390                         length: 17
2391                         [0] u16 command
2392                         [2] u8 action
2393                         [3] v3s16 nodepos_undersurface
2394                         [9] v3s16 nodepos_abovesurface
2395                         [15] u16 item
2396                         actions:
2397                         0: start digging
2398                         1: place block
2399                         2: stop digging (all parameters ignored)
2400                         3: digging completed
2401                 */
2402                 u8 action = readU8(&data[2]);
2403                 v3s16 p_under;
2404                 p_under.X = readS16(&data[3]);
2405                 p_under.Y = readS16(&data[5]);
2406                 p_under.Z = readS16(&data[7]);
2407                 v3s16 p_over;
2408                 p_over.X = readS16(&data[9]);
2409                 p_over.Y = readS16(&data[11]);
2410                 p_over.Z = readS16(&data[13]);
2411                 u16 item_i = readU16(&data[15]);
2412
2413                 //TODO: Check that target is reasonably close
2414                 
2415                 /*
2416                         0: start digging
2417                 */
2418                 if(action == 0)
2419                 {
2420                         /*
2421                                 NOTE: This can be used in the future to check if
2422                                 somebody is cheating, by checking the timing.
2423                         */
2424                 } // action == 0
2425
2426                 /*
2427                         2: stop digging
2428                 */
2429                 else if(action == 2)
2430                 {
2431 #if 0
2432                         RemoteClient *client = getClient(peer_id);
2433                         JMutexAutoLock digmutex(client->m_dig_mutex);
2434                         client->m_dig_tool_item = -1;
2435 #endif
2436                 }
2437
2438                 /*
2439                         3: Digging completed
2440                 */
2441                 else if(action == 3)
2442                 {
2443                         // Mandatory parameter; actually used for nothing
2444                         core::map<v3s16, MapBlock*> modified_blocks;
2445
2446                         content_t material = CONTENT_IGNORE;
2447                         u8 mineral = MINERAL_NONE;
2448
2449                         bool cannot_remove_node = false;
2450
2451                         try
2452                         {
2453                                 MapNode n = m_env->getMap().getNode(p_under);
2454                                 // Get mineral
2455                                 mineral = n.getMineral();
2456                                 // Get material at position
2457                                 material = n.getContent();
2458                                 // If not yet cancelled
2459                                 if(cannot_remove_node == false)
2460                                 {
2461                                         // If it's not diggable, do nothing
2462                                         if(content_diggable(material) == false)
2463                                         {
2464                                                 infostream<<"Server: Not finishing digging: "
2465                                                                 <<"Node not diggable"
2466                                                                 <<std::endl;
2467                                                 cannot_remove_node = true;
2468                                         }
2469                                 }
2470                                 // If not yet cancelled
2471                                 if(cannot_remove_node == false)
2472                                 {
2473                                         // Get node metadata
2474                                         NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
2475                                         if(meta && meta->nodeRemovalDisabled() == true)
2476                                         {
2477                                                 infostream<<"Server: Not finishing digging: "
2478                                                                 <<"Node metadata disables removal"
2479                                                                 <<std::endl;
2480                                                 cannot_remove_node = true;
2481                                         }
2482                                 }
2483                         }
2484                         catch(InvalidPositionException &e)
2485                         {
2486                                 infostream<<"Server: Not finishing digging: Node not found."
2487                                                 <<" Adding block to emerge queue."
2488                                                 <<std::endl;
2489                                 m_emerge_queue.addBlock(peer_id,
2490                                                 getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2491                                 cannot_remove_node = true;
2492                         }
2493
2494                         // Make sure the player is allowed to do it
2495                         if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2496                         {
2497                                 infostream<<"Player "<<player->getName()<<" cannot remove node"
2498                                                 <<" because privileges are "<<getPlayerPrivs(player)
2499                                                 <<std::endl;
2500                                 cannot_remove_node = true;
2501                         }
2502
2503                         /*
2504                                 If node can't be removed, set block to be re-sent to
2505                                 client and quit.
2506                         */
2507                         if(cannot_remove_node)
2508                         {
2509                                 infostream<<"Server: Not finishing digging."<<std::endl;
2510
2511                                 // Client probably has wrong data.
2512                                 // Set block not sent, so that client will get
2513                                 // a valid one.
2514                                 infostream<<"Client "<<peer_id<<" tried to dig "
2515                                                 <<"node; but node cannot be removed."
2516                                                 <<" setting MapBlock not sent."<<std::endl;
2517                                 RemoteClient *client = getClient(peer_id);
2518                                 v3s16 blockpos = getNodeBlockPos(p_under);
2519                                 client->SetBlockNotSent(blockpos);
2520                                         
2521                                 return;
2522                         }
2523                         
2524                         actionstream<<player->getName()<<" digs "<<PP(p_under)
2525                                         <<", gets material "<<(int)material<<", mineral "
2526                                         <<(int)mineral<<std::endl;
2527                         
2528                         /*
2529                                 Send the removal to all close-by players.
2530                                 - If other player is close, send REMOVENODE
2531                                 - Otherwise set blocks not sent
2532                         */
2533                         core::list<u16> far_players;
2534                         sendRemoveNode(p_under, peer_id, &far_players, 30);
2535                         
2536                         /*
2537                                 Update and send inventory
2538                         */
2539
2540                         if(g_settings->getBool("creative_mode") == false)
2541                         {
2542                                 /*
2543                                         Wear out tool
2544                                 */
2545                                 InventoryList *mlist = player->inventory.getList("main");
2546                                 if(mlist != NULL)
2547                                 {
2548                                         InventoryItem *item = mlist->getItem(item_i);
2549                                         if(item && (std::string)item->getName() == "ToolItem")
2550                                         {
2551                                                 ToolItem *titem = (ToolItem*)item;
2552                                                 std::string toolname = titem->getToolName();
2553
2554                                                 // Get digging properties for material and tool
2555                                                 DiggingProperties prop =
2556                                                                 getDiggingProperties(material, toolname);
2557
2558                                                 if(prop.diggable == false)
2559                                                 {
2560                                                         infostream<<"Server: WARNING: Player digged"
2561                                                                         <<" with impossible material + tool"
2562                                                                         <<" combination"<<std::endl;
2563                                                 }
2564                                                 
2565                                                 bool weared_out = titem->addWear(prop.wear);
2566
2567                                                 if(weared_out)
2568                                                 {
2569                                                         mlist->deleteItem(item_i);
2570                                                 }
2571                                         }
2572                                 }
2573
2574                                 /*
2575                                         Add dug item to inventory
2576                                 */
2577
2578                                 InventoryItem *item = NULL;
2579
2580                                 if(mineral != MINERAL_NONE)
2581                                         item = getDiggedMineralItem(mineral);
2582                                 
2583                                 // If not mineral
2584                                 if(item == NULL)
2585                                 {
2586                                         std::string &dug_s = content_features(material).dug_item;
2587                                         if(dug_s != "")
2588                                         {
2589                                                 std::istringstream is(dug_s, std::ios::binary);
2590                                                 item = InventoryItem::deSerialize(is);
2591                                         }
2592                                 }
2593                                 
2594                                 if(item != NULL)
2595                                 {
2596                                         // Add a item to inventory
2597                                         player->inventory.addItem("main", item);
2598
2599                                         // Send inventory
2600                                         UpdateCrafting(player->peer_id);
2601                                         SendInventory(player->peer_id);
2602                                 }
2603
2604                                 item = NULL;
2605
2606                                 if(mineral != MINERAL_NONE)
2607                                   item = getDiggedMineralItem(mineral);
2608                         
2609                                 // If not mineral
2610                                 if(item == NULL)
2611                                 {
2612                                         std::string &extra_dug_s = content_features(material).extra_dug_item;
2613                                         s32 extra_rarity = content_features(material).extra_dug_item_rarity;
2614                                         if(extra_dug_s != "" && extra_rarity != 0
2615                                            && myrand() % extra_rarity == 0)
2616                                         {
2617                                                 std::istringstream is(extra_dug_s, std::ios::binary);
2618                                                 item = InventoryItem::deSerialize(is);
2619                                         }
2620                                 }
2621                         
2622                                 if(item != NULL)
2623                                 {
2624                                         // Add a item to inventory
2625                                         player->inventory.addItem("main", item);
2626
2627                                         // Send inventory
2628                                         UpdateCrafting(player->peer_id);
2629                                         SendInventory(player->peer_id);
2630                                 }
2631                         }
2632
2633                         /*
2634                                 Remove the node
2635                                 (this takes some time so it is done after the quick stuff)
2636                         */
2637                         {
2638                                 MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2639
2640                                 m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
2641                         }
2642                         /*
2643                                 Set blocks not sent to far players
2644                         */
2645                         for(core::list<u16>::Iterator
2646                                         i = far_players.begin();
2647                                         i != far_players.end(); i++)
2648                         {
2649                                 u16 peer_id = *i;
2650                                 RemoteClient *client = getClient(peer_id);
2651                                 if(client==NULL)
2652                                         continue;
2653                                 client->SetBlocksNotSent(modified_blocks);
2654                         }
2655                 }
2656                 
2657                 /*
2658                         1: place block
2659                 */
2660                 else if(action == 1)
2661                 {
2662
2663                         InventoryList *ilist = player->inventory.getList("main");
2664                         if(ilist == NULL)
2665                                 return;
2666
2667                         // Get item
2668                         InventoryItem *item = ilist->getItem(item_i);
2669                         
2670                         // If there is no item, it is not possible to add it anywhere
2671                         if(item == NULL)
2672                                 return;
2673                         
2674                         /*
2675                                 Handle material items
2676                         */
2677                         if(std::string("MaterialItem") == item->getName())
2678                         {
2679                                 try{
2680                                         // Don't add a node if this is not a free space
2681                                         MapNode n2 = m_env->getMap().getNode(p_over);
2682                                         bool no_enough_privs =
2683                                                         ((getPlayerPrivs(player) & PRIV_BUILD)==0);
2684                                         if(no_enough_privs)
2685                                                 infostream<<"Player "<<player->getName()<<" cannot add node"
2686                                                         <<" because privileges are "<<getPlayerPrivs(player)
2687                                                         <<std::endl;
2688
2689                                         if(content_features(n2).buildable_to == false
2690                                                 || no_enough_privs)
2691                                         {
2692                                                 // Client probably has wrong data.
2693                                                 // Set block not sent, so that client will get
2694                                                 // a valid one.
2695                                                 infostream<<"Client "<<peer_id<<" tried to place"
2696                                                                 <<" node in invalid position; setting"
2697                                                                 <<" MapBlock not sent."<<std::endl;
2698                                                 RemoteClient *client = getClient(peer_id);
2699                                                 v3s16 blockpos = getNodeBlockPos(p_over);
2700                                                 client->SetBlockNotSent(blockpos);
2701                                                 return;
2702                                         }
2703                                 }
2704                                 catch(InvalidPositionException &e)
2705                                 {
2706                                         infostream<<"Server: Ignoring ADDNODE: Node not found"
2707                                                         <<" Adding block to emerge queue."
2708                                                         <<std::endl;
2709                                         m_emerge_queue.addBlock(peer_id,
2710                                                         getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2711                                         return;
2712                                 }
2713
2714                                 // Reset build time counter
2715                                 getClient(peer_id)->m_time_from_building = 0.0;
2716                                 
2717                                 // Create node data
2718                                 MaterialItem *mitem = (MaterialItem*)item;
2719                                 MapNode n;
2720                                 n.setContent(mitem->getMaterial());
2721
2722                                 actionstream<<player->getName()<<" places material "
2723                                                 <<(int)mitem->getMaterial()
2724                                                 <<" at "<<PP(p_under)<<std::endl;
2725                         
2726                                 // Calculate direction for wall mounted stuff
2727                                 if(content_features(n).wall_mounted)
2728                                         n.param2 = packDir(p_under - p_over);
2729
2730                                 // Calculate the direction for furnaces and chests and stuff
2731                                 if(content_features(n).param_type == CPT_FACEDIR_SIMPLE)
2732                                 {
2733                                         v3f playerpos = player->getPosition();
2734                                         v3f blockpos = intToFloat(p_over, BS) - playerpos;
2735                                         blockpos = blockpos.normalize();
2736                                         n.param1 = 0;
2737                                         if (fabs(blockpos.X) > fabs(blockpos.Z)) {
2738                                                 if (blockpos.X < 0)
2739                                                         n.param1 = 3;
2740                                                 else
2741                                                         n.param1 = 1;
2742                                         } else {
2743                                                 if (blockpos.Z < 0)
2744                                                         n.param1 = 2;
2745                                                 else
2746                                                         n.param1 = 0;
2747                                         }
2748                                 }
2749
2750                                 /*
2751                                         Send to all close-by players
2752                                 */
2753                                 core::list<u16> far_players;
2754                                 sendAddNode(p_over, n, 0, &far_players, 30);
2755                                 
2756                                 /*
2757                                         Handle inventory
2758                                 */
2759                                 InventoryList *ilist = player->inventory.getList("main");
2760                                 if(g_settings->getBool("creative_mode") == false && ilist)
2761                                 {
2762                                         // Remove from inventory and send inventory
2763                                         if(mitem->getCount() == 1)
2764                                                 ilist->deleteItem(item_i);
2765                                         else
2766                                                 mitem->remove(1);
2767                                         // Send inventory
2768                                         UpdateCrafting(peer_id);
2769                                         SendInventory(peer_id);
2770                                 }
2771                                 
2772                                 /*
2773                                         Add node.
2774
2775                                         This takes some time so it is done after the quick stuff
2776                                 */
2777                                 core::map<v3s16, MapBlock*> modified_blocks;
2778                                 {
2779                                         MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2780
2781                                         std::string p_name = std::string(player->getName());
2782                                         m_env->getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
2783                                 }
2784                                 /*
2785                                         Set blocks not sent to far players
2786                                 */
2787                                 for(core::list<u16>::Iterator
2788                                                 i = far_players.begin();
2789                                                 i != far_players.end(); i++)
2790                                 {
2791                                         u16 peer_id = *i;
2792                                         RemoteClient *client = getClient(peer_id);
2793                                         if(client==NULL)
2794                                                 continue;
2795                                         client->SetBlocksNotSent(modified_blocks);
2796                                 }
2797
2798                                 /*
2799                                         Calculate special events
2800                                 */
2801                                 
2802                                 /*if(n.d == CONTENT_MESE)
2803                                 {
2804                                         u32 count = 0;
2805                                         for(s16 z=-1; z<=1; z++)
2806                                         for(s16 y=-1; y<=1; y++)
2807                                         for(s16 x=-1; x<=1; x++)
2808                                         {
2809                                                 
2810                                         }
2811                                 }*/
2812                         }
2813                         /*
2814                                 Place other item (not a block)
2815                         */
2816                         else
2817                         {
2818                                 v3s16 blockpos = getNodeBlockPos(p_over);
2819                                 
2820                                 /*
2821                                         Check that the block is loaded so that the item
2822                                         can properly be added to the static list too
2823                                 */
2824                                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
2825                                 if(block==NULL)
2826                                 {
2827                                         infostream<<"Error while placing object: "
2828                                                         "block not found"<<std::endl;
2829                                         return;
2830                                 }
2831
2832                                 /*
2833                                         If in creative mode, item dropping is disabled unless
2834                                         player has build privileges
2835                                 */
2836                                 if(g_settings->getBool("creative_mode") &&
2837                                         (getPlayerPrivs(player) & PRIV_BUILD) == 0)
2838                                 {
2839                                         infostream<<"Not allowing player to drop item: "
2840                                                         "creative mode and no build privs"<<std::endl;
2841                                         return;
2842                                 }
2843
2844                                 // Calculate a position for it
2845                                 v3f pos = intToFloat(p_over, BS);
2846                                 //pos.Y -= BS*0.45;
2847                                 pos.Y -= BS*0.25; // let it drop a bit
2848                                 // Randomize a bit
2849                                 pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2850                                 pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2851
2852                                 /*
2853                                         Create the object
2854                                 */
2855                                 ServerActiveObject *obj = item->createSAO(m_env, 0, pos);
2856
2857                                 if(obj == NULL)
2858                                 {
2859                                         infostream<<"WARNING: item resulted in NULL object, "
2860                                                         <<"not placing onto map"
2861                                                         <<std::endl;
2862                                 }
2863                                 else
2864                                 {
2865                                         actionstream<<player->getName()<<" places "<<item->getName()
2866                                                         <<" at "<<PP(p_over)<<std::endl;
2867                                 
2868                                         // Add the object to the environment
2869                                         m_env->addActiveObject(obj);
2870                                         
2871                                         infostream<<"Placed object"<<std::endl;
2872
2873                                         if(g_settings->getBool("creative_mode") == false)
2874                                         {
2875                                                 // Delete the right amount of items from the slot
2876                                                 u16 dropcount = item->getDropCount();
2877                                                 
2878                                                 // Delete item if all gone
2879                                                 if(item->getCount() <= dropcount)
2880                                                 {
2881                                                         if(item->getCount() < dropcount)
2882                                                                 infostream<<"WARNING: Server: dropped more items"
2883                                                                                 <<" than the slot contains"<<std::endl;
2884                                                         
2885                                                         InventoryList *ilist = player->inventory.getList("main");
2886                                                         if(ilist)
2887                                                                 // Remove from inventory and send inventory
2888                                                                 ilist->deleteItem(item_i);
2889                                                 }
2890                                                 // Else decrement it
2891                                                 else
2892                                                         item->remove(dropcount);
2893                                                 
2894                                                 // Send inventory
2895                                                 UpdateCrafting(peer_id);
2896                                                 SendInventory(peer_id);
2897                                         }
2898                                 }
2899                         }
2900
2901                 } // action == 1
2902
2903                 /*
2904                         Catch invalid actions
2905                 */
2906                 else
2907                 {
2908                         infostream<<"WARNING: Server: Invalid action "
2909                                         <<action<<std::endl;
2910                 }
2911         }
2912 #if 0
2913         else if(command == TOSERVER_RELEASE)
2914         {
2915                 if(datasize < 3)
2916                         return;
2917                 /*
2918                         length: 3
2919                         [0] u16 command
2920                         [2] u8 button
2921                 */
2922                 infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
2923         }
2924 #endif
2925         else if(command == TOSERVER_SIGNTEXT)
2926         {
2927                 infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
2928                                 <<std::endl;
2929                 return;
2930         }
2931         else if(command == TOSERVER_SIGNNODETEXT)
2932         {
2933                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2934                         return;
2935                 /*
2936                         u16 command
2937                         v3s16 p
2938                         u16 textlen
2939                         textdata
2940                 */
2941                 std::string datastring((char*)&data[2], datasize-2);
2942                 std::istringstream is(datastring, std::ios_base::binary);
2943                 u8 buf[6];
2944                 // Read stuff
2945                 is.read((char*)buf, 6);
2946                 v3s16 p = readV3S16(buf);
2947                 is.read((char*)buf, 2);
2948                 u16 textlen = readU16(buf);
2949                 std::string text;
2950                 for(u16 i=0; i<textlen; i++)
2951                 {
2952                         is.read((char*)buf, 1);
2953                         text += (char)buf[0];
2954                 }
2955
2956                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
2957                 if(!meta)
2958                         return;
2959                 if(meta->typeId() != CONTENT_SIGN_WALL)
2960                         return;
2961                 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
2962                 signmeta->setText(text);
2963                 
2964                 actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
2965                                 <<" at "<<PP(p)<<std::endl;
2966                                 
2967                 v3s16 blockpos = getNodeBlockPos(p);
2968                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
2969                 if(block)
2970                 {
2971                         block->setChangedFlag();
2972                 }
2973
2974                 for(core::map<u16, RemoteClient*>::Iterator
2975                         i = m_clients.getIterator();
2976                         i.atEnd()==false; i++)
2977                 {
2978                         RemoteClient *client = i.getNode()->getValue();
2979                         client->SetBlockNotSent(blockpos);
2980                 }
2981         }
2982         else if(command == TOSERVER_INVENTORY_ACTION)
2983         {
2984                 /*// Ignore inventory changes if in creative mode
2985                 if(g_settings->getBool("creative_mode") == true)
2986                 {
2987                         infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
2988                                         <<std::endl;
2989                         return;
2990                 }*/
2991                 // Strip command and create a stream
2992                 std::string datastring((char*)&data[2], datasize-2);
2993                 infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
2994                 std::istringstream is(datastring, std::ios_base::binary);
2995                 // Create an action
2996                 InventoryAction *a = InventoryAction::deSerialize(is);
2997                 if(a != NULL)
2998                 {
2999                         // Create context
3000                         InventoryContext c;
3001                         c.current_player = player;
3002
3003                         /*
3004                                 Handle craftresult specially if not in creative mode
3005                         */
3006                         bool disable_action = false;
3007                         if(a->getType() == IACTION_MOVE
3008                                         && g_settings->getBool("creative_mode") == false)
3009                         {
3010                                 IMoveAction *ma = (IMoveAction*)a;
3011                                 if(ma->to_inv == "current_player" &&
3012                                                 ma->from_inv == "current_player")
3013                                 {
3014                                         InventoryList *rlist = player->inventory.getList("craftresult");
3015                                         assert(rlist);
3016                                         InventoryList *clist = player->inventory.getList("craft");
3017                                         assert(clist);
3018                                         InventoryList *mlist = player->inventory.getList("main");
3019                                         assert(mlist);
3020                                         /*
3021                                                 Craftresult is no longer preview if something
3022                                                 is moved into it
3023                                         */
3024                                         if(ma->to_list == "craftresult"
3025                                                         && ma->from_list != "craftresult")
3026                                         {
3027                                                 // If it currently is a preview, remove
3028                                                 // its contents
3029                                                 if(player->craftresult_is_preview)
3030                                                 {
3031                                                         rlist->deleteItem(0);
3032                                                 }
3033                                                 player->craftresult_is_preview = false;
3034                                         }
3035                                         /*
3036                                                 Crafting takes place if this condition is true.
3037                                         */
3038                                         if(player->craftresult_is_preview &&
3039                                                         ma->from_list == "craftresult")
3040                                         {
3041                                                 player->craftresult_is_preview = false;
3042                                                 clist->decrementMaterials(1);
3043                                                 
3044                                                 /* Print out action */
3045                                                 InventoryList *list =
3046                                                                 player->inventory.getList("craftresult");
3047                                                 assert(list);
3048                                                 InventoryItem *item = list->getItem(0);
3049                                                 std::string itemname = "NULL";
3050                                                 if(item)
3051                                                         itemname = item->getName();
3052                                                 actionstream<<player->getName()<<" crafts "
3053                                                                 <<itemname<<std::endl;
3054                                         }
3055                                         /*
3056                                                 If the craftresult is placed on itself, move it to
3057                                                 main inventory instead of doing the action
3058                                         */
3059                                         if(ma->to_list == "craftresult"
3060                                                         && ma->from_list == "craftresult")
3061                                         {
3062                                                 disable_action = true;
3063                                                 
3064                                                 InventoryItem *item1 = rlist->changeItem(0, NULL);
3065                                                 mlist->addItem(item1);
3066                                         }
3067                                 }
3068                                 // Disallow moving items if not allowed to build
3069                                 else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
3070                                 {
3071                                         return;
3072                                 }
3073                                 // if it's a locking chest, only allow the owner or server admins to move items
3074                                 else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3075                                 {
3076                                         Strfnd fn(ma->from_inv);
3077                                         std::string id0 = fn.next(":");
3078                                         if(id0 == "nodemeta")
3079                                         {
3080                                                 v3s16 p;
3081                                                 p.X = stoi(fn.next(","));
3082                                                 p.Y = stoi(fn.next(","));
3083                                                 p.Z = stoi(fn.next(","));
3084                                                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3085                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3086                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3087                                                         if (lcm->getOwner() != player->getName())
3088                                                                 return;
3089                                                 }
3090                                         }
3091                                 }
3092                                 else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3093                                 {
3094                                         Strfnd fn(ma->to_inv);
3095                                         std::string id0 = fn.next(":");
3096                                         if(id0 == "nodemeta")
3097                                         {
3098                                                 v3s16 p;
3099                                                 p.X = stoi(fn.next(","));
3100                                                 p.Y = stoi(fn.next(","));
3101                                                 p.Z = stoi(fn.next(","));
3102                                                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3103                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3104                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3105                                                         if (lcm->getOwner() != player->getName())
3106                                                                 return;
3107                                                 }
3108                                         }
3109                                 }
3110                         }
3111                         
3112                         if(disable_action == false)
3113                         {
3114                                 // Feed action to player inventory
3115                                 a->apply(&c, this);
3116                                 // Eat the action
3117                                 delete a;
3118                         }
3119                         else
3120                         {
3121                                 // Send inventory
3122                                 UpdateCrafting(player->peer_id);
3123                                 SendInventory(player->peer_id);
3124                         }
3125                 }
3126                 else
3127                 {
3128                         infostream<<"TOSERVER_INVENTORY_ACTION: "
3129                                         <<"InventoryAction::deSerialize() returned NULL"
3130                                         <<std::endl;
3131                 }
3132         }
3133         else if(command == TOSERVER_CHAT_MESSAGE)
3134         {
3135                 /*
3136                         u16 command
3137                         u16 length
3138                         wstring message
3139                 */
3140                 u8 buf[6];
3141                 std::string datastring((char*)&data[2], datasize-2);
3142                 std::istringstream is(datastring, std::ios_base::binary);
3143                 
3144                 // Read stuff
3145                 is.read((char*)buf, 2);
3146                 u16 len = readU16(buf);
3147                 
3148                 std::wstring message;
3149                 for(u16 i=0; i<len; i++)
3150                 {
3151                         is.read((char*)buf, 2);
3152                         message += (wchar_t)readU16(buf);
3153                 }
3154
3155                 // Get player name of this client
3156                 std::wstring name = narrow_to_wide(player->getName());
3157                 
3158                 // Line to send to players
3159                 std::wstring line;
3160                 // Whether to send to the player that sent the line
3161                 bool send_to_sender = false;
3162                 // Whether to send to other players
3163                 bool send_to_others = false;
3164                 
3165                 // Local player gets all privileges regardless of
3166                 // what's set on their account.
3167                 u64 privs = getPlayerPrivs(player);
3168
3169                 // Parse commands
3170                 if(message[0] == L'/')
3171                 {
3172                         size_t strip_size = 1;
3173                         if (message[1] == L'#') // support old-style commans
3174                                 ++strip_size;
3175                         message = message.substr(strip_size);
3176
3177                         WStrfnd f1(message);
3178                         f1.next(L" "); // Skip over /#whatever
3179                         std::wstring paramstring = f1.next(L"");
3180
3181                         ServerCommandContext *ctx = new ServerCommandContext(
3182                                 str_split(message, L' '),
3183                                 paramstring,
3184                                 this,
3185                                 m_env,
3186                                 player,
3187                                 privs);
3188
3189                         std::wstring reply(processServerCommand(ctx));
3190                         send_to_sender = ctx->flags & SEND_TO_SENDER;
3191                         send_to_others = ctx->flags & SEND_TO_OTHERS;
3192
3193                         if (ctx->flags & SEND_NO_PREFIX)
3194                                 line += reply;
3195                         else
3196                                 line += L"Server: " + reply;
3197
3198                         delete ctx;
3199
3200                 }
3201                 else
3202                 {
3203                         if(privs & PRIV_SHOUT)
3204                         {
3205                                 line += L"<";
3206                                 line += name;
3207                                 line += L"> ";
3208                                 line += message;
3209                                 send_to_others = true;
3210                         }
3211                         else
3212                         {
3213                                 line += L"Server: You are not allowed to shout";
3214                                 send_to_sender = true;
3215                         }
3216                 }
3217                 
3218                 if(line != L"")
3219                 {
3220                         if(send_to_others)
3221                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
3222
3223                         /*
3224                                 Send the message to clients
3225                         */
3226                         for(core::map<u16, RemoteClient*>::Iterator
3227                                 i = m_clients.getIterator();
3228                                 i.atEnd() == false; i++)
3229                         {
3230                                 // Get client and check that it is valid
3231                                 RemoteClient *client = i.getNode()->getValue();
3232                                 assert(client->peer_id == i.getNode()->getKey());
3233                                 if(client->serialization_version == SER_FMT_VER_INVALID)
3234                                         continue;
3235
3236                                 // Filter recipient
3237                                 bool sender_selected = (peer_id == client->peer_id);
3238                                 if(sender_selected == true && send_to_sender == false)
3239                                         continue;
3240                                 if(sender_selected == false && send_to_others == false)
3241                                         continue;
3242
3243                                 SendChatMessage(client->peer_id, line);
3244                         }
3245                 }
3246         }
3247         else if(command == TOSERVER_DAMAGE)
3248         {
3249                 std::string datastring((char*)&data[2], datasize-2);
3250                 std::istringstream is(datastring, std::ios_base::binary);
3251                 u8 damage = readU8(is);
3252
3253                 if(g_settings->getBool("enable_damage"))
3254                 {
3255                         actionstream<<player->getName()<<" damaged by "
3256                                         <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
3257                                         <<std::endl;
3258                                 
3259                         HandlePlayerHP(player, damage);
3260                 }
3261                 else
3262                 {
3263                         SendPlayerHP(player);
3264                 }
3265         }
3266         else if(command == TOSERVER_PASSWORD)
3267         {
3268                 /*
3269                         [0] u16 TOSERVER_PASSWORD
3270                         [2] u8[28] old password
3271                         [30] u8[28] new password
3272                 */
3273
3274                 if(datasize != 2+PASSWORD_SIZE*2)
3275                         return;
3276                 /*char password[PASSWORD_SIZE];
3277                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3278                         password[i] = data[2+i];
3279                 password[PASSWORD_SIZE-1] = 0;*/
3280                 std::string oldpwd;
3281                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3282                 {
3283                         char c = data[2+i];
3284                         if(c == 0)
3285                                 break;
3286                         oldpwd += c;
3287                 }
3288                 std::string newpwd;
3289                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3290                 {
3291                         char c = data[2+PASSWORD_SIZE+i];
3292                         if(c == 0)
3293                                 break;
3294                         newpwd += c;
3295                 }
3296
3297                 infostream<<"Server: Client requests a password change from "
3298                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
3299
3300                 std::string playername = player->getName();
3301
3302                 if(m_authmanager.exists(playername) == false)
3303                 {
3304                         infostream<<"Server: playername not found in authmanager"<<std::endl;
3305                         // Wrong old password supplied!!
3306                         SendChatMessage(peer_id, L"playername not found in authmanager");
3307                         return;
3308                 }
3309
3310                 std::string checkpwd = m_authmanager.getPassword(playername);
3311
3312                 if(oldpwd != checkpwd)
3313                 {
3314                         infostream<<"Server: invalid old password"<<std::endl;
3315                         // Wrong old password supplied!!
3316                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
3317                         return;
3318                 }
3319
3320                 actionstream<<player->getName()<<" changes password"<<std::endl;
3321
3322                 m_authmanager.setPassword(playername, newpwd);
3323                 
3324                 infostream<<"Server: password change successful for "<<playername
3325                                 <<std::endl;
3326                 SendChatMessage(peer_id, L"Password change successful");
3327         }
3328         else if(command == TOSERVER_PLAYERITEM)
3329         {
3330                 if (datasize < 2+2)
3331                         return;
3332
3333                 u16 item = readU16(&data[2]);
3334                 player->wieldItem(item);
3335                 SendWieldedItem(player);
3336         }
3337         else if(command == TOSERVER_RESPAWN)
3338         {
3339                 if(player->hp != 0)
3340                         return;
3341                 
3342                 RespawnPlayer(player);
3343                 
3344                 actionstream<<player->getName()<<" respawns at "
3345                                 <<PP(player->getPosition()/BS)<<std::endl;
3346         }
3347         else
3348         {
3349                 infostream<<"Server::ProcessData(): Ignoring "
3350                                 "unknown command "<<command<<std::endl;
3351         }
3352         
3353         } //try
3354         catch(SendFailedException &e)
3355         {
3356                 errorstream<<"Server::ProcessData(): SendFailedException: "
3357                                 <<"what="<<e.what()
3358                                 <<std::endl;
3359         }
3360 }
3361
3362 void Server::onMapEditEvent(MapEditEvent *event)
3363 {
3364         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3365         if(m_ignore_map_edit_events)
3366                 return;
3367         MapEditEvent *e = event->clone();
3368         m_unsent_map_edit_queue.push_back(e);
3369 }
3370
3371 Inventory* Server::getInventory(InventoryContext *c, std::string id)
3372 {
3373         if(id == "current_player")
3374         {
3375                 assert(c->current_player);
3376                 return &(c->current_player->inventory);
3377         }
3378         
3379         Strfnd fn(id);
3380         std::string id0 = fn.next(":");
3381
3382         if(id0 == "nodemeta")
3383         {
3384                 v3s16 p;
3385                 p.X = stoi(fn.next(","));
3386                 p.Y = stoi(fn.next(","));
3387                 p.Z = stoi(fn.next(","));
3388                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3389                 if(meta)
3390                         return meta->getInventory();
3391                 infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
3392                                 <<"no metadata found"<<std::endl;
3393                 return NULL;
3394         }
3395
3396         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3397         return NULL;
3398 }
3399 void Server::inventoryModified(InventoryContext *c, std::string id)
3400 {
3401         if(id == "current_player")
3402         {
3403                 assert(c->current_player);
3404                 // Send inventory
3405                 UpdateCrafting(c->current_player->peer_id);
3406                 SendInventory(c->current_player->peer_id);
3407                 return;
3408         }
3409         
3410         Strfnd fn(id);
3411         std::string id0 = fn.next(":");
3412
3413         if(id0 == "nodemeta")
3414         {
3415                 v3s16 p;
3416                 p.X = stoi(fn.next(","));
3417                 p.Y = stoi(fn.next(","));
3418                 p.Z = stoi(fn.next(","));
3419                 v3s16 blockpos = getNodeBlockPos(p);
3420
3421                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3422                 if(meta)
3423                         meta->inventoryModified();
3424
3425                 for(core::map<u16, RemoteClient*>::Iterator
3426                         i = m_clients.getIterator();
3427                         i.atEnd()==false; i++)
3428                 {
3429                         RemoteClient *client = i.getNode()->getValue();
3430                         client->SetBlockNotSent(blockpos);
3431                 }
3432
3433                 return;
3434         }
3435
3436         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3437 }
3438
3439 core::list<PlayerInfo> Server::getPlayerInfo()
3440 {
3441         DSTACK(__FUNCTION_NAME);
3442         JMutexAutoLock envlock(m_env_mutex);
3443         JMutexAutoLock conlock(m_con_mutex);
3444         
3445         core::list<PlayerInfo> list;
3446
3447         core::list<Player*> players = m_env->getPlayers();
3448         
3449         core::list<Player*>::Iterator i;
3450         for(i = players.begin();
3451                         i != players.end(); i++)
3452         {
3453                 PlayerInfo info;
3454
3455                 Player *player = *i;
3456
3457                 try{
3458                         // Copy info from connection to info struct
3459                         info.id = player->peer_id;
3460                         info.address = m_con.GetPeerAddress(player->peer_id);
3461                         info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
3462                 }
3463                 catch(con::PeerNotFoundException &e)
3464                 {
3465                         // Set dummy peer info
3466                         info.id = 0;
3467                         info.address = Address(0,0,0,0,0);
3468                         info.avg_rtt = 0.0;
3469                 }
3470
3471                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3472                 info.position = player->getPosition();
3473
3474                 list.push_back(info);
3475         }
3476
3477         return list;
3478 }
3479
3480
3481 void Server::peerAdded(con::Peer *peer)
3482 {
3483         DSTACK(__FUNCTION_NAME);
3484         infostream<<"Server::peerAdded(): peer->id="
3485                         <<peer->id<<std::endl;
3486         
3487         PeerChange c;
3488         c.type = PEER_ADDED;
3489         c.peer_id = peer->id;
3490         c.timeout = false;
3491         m_peer_change_queue.push_back(c);
3492 }
3493
3494 void Server::deletingPeer(con::Peer *peer, bool timeout)
3495 {
3496         DSTACK(__FUNCTION_NAME);
3497         infostream<<"Server::deletingPeer(): peer->id="
3498                         <<peer->id<<", timeout="<<timeout<<std::endl;
3499         
3500         PeerChange c;
3501         c.type = PEER_REMOVED;
3502         c.peer_id = peer->id;
3503         c.timeout = timeout;
3504         m_peer_change_queue.push_back(c);
3505 }
3506
3507 /*
3508         Static send methods
3509 */
3510
3511 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3512 {
3513         DSTACK(__FUNCTION_NAME);
3514         std::ostringstream os(std::ios_base::binary);
3515
3516         writeU16(os, TOCLIENT_HP);
3517         writeU8(os, hp);
3518
3519         // Make data buffer
3520         std::string s = os.str();
3521         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3522         // Send as reliable
3523         con.Send(peer_id, 0, data, true);
3524 }
3525
3526 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3527                 const std::wstring &reason)
3528 {
3529         DSTACK(__FUNCTION_NAME);
3530         std::ostringstream os(std::ios_base::binary);
3531
3532         writeU16(os, TOCLIENT_ACCESS_DENIED);
3533         os<<serializeWideString(reason);
3534
3535         // Make data buffer
3536         std::string s = os.str();
3537         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3538         // Send as reliable
3539         con.Send(peer_id, 0, data, true);
3540 }
3541
3542 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3543                 bool set_camera_point_target, v3f camera_point_target)
3544 {
3545         DSTACK(__FUNCTION_NAME);
3546         std::ostringstream os(std::ios_base::binary);
3547
3548         writeU16(os, TOCLIENT_DEATHSCREEN);
3549         writeU8(os, set_camera_point_target);
3550         writeV3F1000(os, camera_point_target);
3551
3552         // Make data buffer
3553         std::string s = os.str();
3554         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3555         // Send as reliable
3556         con.Send(peer_id, 0, data, true);
3557 }
3558
3559 /*
3560         Non-static send methods
3561 */
3562
3563 void Server::SendObjectData(float dtime)
3564 {
3565         DSTACK(__FUNCTION_NAME);
3566
3567         core::map<v3s16, bool> stepped_blocks;
3568         
3569         for(core::map<u16, RemoteClient*>::Iterator
3570                 i = m_clients.getIterator();
3571                 i.atEnd() == false; i++)
3572         {
3573                 u16 peer_id = i.getNode()->getKey();
3574                 RemoteClient *client = i.getNode()->getValue();
3575                 assert(client->peer_id == peer_id);
3576                 
3577                 if(client->serialization_version == SER_FMT_VER_INVALID)
3578                         continue;
3579                 
3580                 client->SendObjectData(this, dtime, stepped_blocks);
3581         }
3582 }
3583
3584 void Server::SendPlayerInfos()
3585 {
3586         DSTACK(__FUNCTION_NAME);
3587
3588         //JMutexAutoLock envlock(m_env_mutex);
3589         
3590         // Get connected players
3591         core::list<Player*> players = m_env->getPlayers(true);
3592         
3593         u32 player_count = players.getSize();
3594         u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
3595
3596         SharedBuffer<u8> data(datasize);
3597         writeU16(&data[0], TOCLIENT_PLAYERINFO);
3598         
3599         u32 start = 2;
3600         core::list<Player*>::Iterator i;
3601         for(i = players.begin();
3602                         i != players.end(); i++)
3603         {
3604                 Player *player = *i;
3605
3606                 /*infostream<<"Server sending player info for player with "
3607                                 "peer_id="<<player->peer_id<<std::endl;*/
3608                 
3609                 writeU16(&data[start], player->peer_id);
3610                 memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
3611                 snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
3612                 start += 2+PLAYERNAME_SIZE;
3613         }
3614
3615         //JMutexAutoLock conlock(m_con_mutex);
3616
3617         // Send as reliable
3618         m_con.SendToAll(0, data, true);
3619 }
3620
3621 void Server::SendInventory(u16 peer_id)
3622 {
3623         DSTACK(__FUNCTION_NAME);
3624         
3625         Player* player = m_env->getPlayer(peer_id);
3626         assert(player);
3627
3628         /*
3629                 Serialize it
3630         */
3631
3632         std::ostringstream os;
3633         //os.imbue(std::locale("C"));
3634
3635         player->inventory.serialize(os);
3636
3637         std::string s = os.str();
3638         
3639         SharedBuffer<u8> data(s.size()+2);
3640         writeU16(&data[0], TOCLIENT_INVENTORY);
3641         memcpy(&data[2], s.c_str(), s.size());
3642         
3643         // Send as reliable
3644         m_con.Send(peer_id, 0, data, true);
3645 }
3646
3647 std::string getWieldedItemString(const Player *player)
3648 {
3649         const InventoryItem *item = player->getWieldItem();
3650         if (item == NULL)
3651                 return std::string("");
3652         std::ostringstream os(std::ios_base::binary);
3653         item->serialize(os);
3654         return os.str();
3655 }
3656
3657 void Server::SendWieldedItem(const Player* player)
3658 {
3659         DSTACK(__FUNCTION_NAME);
3660
3661         assert(player);
3662
3663         std::ostringstream os(std::ios_base::binary);
3664
3665         writeU16(os, TOCLIENT_PLAYERITEM);
3666         writeU16(os, 1);
3667         writeU16(os, player->peer_id);
3668         os<<serializeString(getWieldedItemString(player));
3669
3670         // Make data buffer
3671         std::string s = os.str();
3672         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3673
3674         m_con.SendToAll(0, data, true);
3675 }
3676
3677 void Server::SendPlayerItems()
3678 {
3679         DSTACK(__FUNCTION_NAME);
3680
3681         std::ostringstream os(std::ios_base::binary);
3682         core::list<Player *> players = m_env->getPlayers(true);
3683
3684         writeU16(os, TOCLIENT_PLAYERITEM);
3685         writeU16(os, players.size());
3686         core::list<Player *>::Iterator i;
3687         for(i = players.begin(); i != players.end(); ++i)
3688         {
3689                 Player *p = *i;
3690                 writeU16(os, p->peer_id);
3691                 os<<serializeString(getWieldedItemString(p));
3692         }
3693
3694         // Make data buffer
3695         std::string s = os.str();
3696         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3697
3698         m_con.SendToAll(0, data, true);
3699 }
3700
3701 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3702 {
3703         DSTACK(__FUNCTION_NAME);
3704         
3705         std::ostringstream os(std::ios_base::binary);
3706         u8 buf[12];
3707         
3708         // Write command
3709         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3710         os.write((char*)buf, 2);
3711         
3712         // Write length
3713         writeU16(buf, message.size());
3714         os.write((char*)buf, 2);
3715         
3716         // Write string
3717         for(u32 i=0; i<message.size(); i++)
3718         {
3719                 u16 w = message[i];
3720                 writeU16(buf, w);
3721                 os.write((char*)buf, 2);
3722         }
3723         
3724         // Make data buffer
3725         std::string s = os.str();
3726         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3727         // Send as reliable
3728         m_con.Send(peer_id, 0, data, true);
3729 }
3730
3731 void Server::BroadcastChatMessage(const std::wstring &message)
3732 {
3733         for(core::map<u16, RemoteClient*>::Iterator
3734                 i = m_clients.getIterator();
3735                 i.atEnd() == false; i++)
3736         {
3737                 // Get client and check that it is valid
3738                 RemoteClient *client = i.getNode()->getValue();
3739                 assert(client->peer_id == i.getNode()->getKey());
3740                 if(client->serialization_version == SER_FMT_VER_INVALID)
3741                         continue;
3742
3743                 SendChatMessage(client->peer_id, message);
3744         }
3745 }
3746
3747 void Server::SendPlayerHP(Player *player)
3748 {
3749         SendHP(m_con, player->peer_id, player->hp);
3750 }
3751
3752 void Server::SendMovePlayer(Player *player)
3753 {
3754         DSTACK(__FUNCTION_NAME);
3755         std::ostringstream os(std::ios_base::binary);
3756
3757         writeU16(os, TOCLIENT_MOVE_PLAYER);
3758         writeV3F1000(os, player->getPosition());
3759         writeF1000(os, player->getPitch());
3760         writeF1000(os, player->getYaw());
3761         
3762         {
3763                 v3f pos = player->getPosition();
3764                 f32 pitch = player->getPitch();
3765                 f32 yaw = player->getYaw();
3766                 infostream<<"Server sending TOCLIENT_MOVE_PLAYER"
3767                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3768                                 <<" pitch="<<pitch
3769                                 <<" yaw="<<yaw
3770                                 <<std::endl;
3771         }
3772
3773         // Make data buffer
3774         std::string s = os.str();
3775         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3776         // Send as reliable
3777         m_con.Send(player->peer_id, 0, data, true);
3778 }
3779
3780 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3781         core::list<u16> *far_players, float far_d_nodes)
3782 {
3783         float maxd = far_d_nodes*BS;
3784         v3f p_f = intToFloat(p, BS);
3785
3786         // Create packet
3787         u32 replysize = 8;
3788         SharedBuffer<u8> reply(replysize);
3789         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3790         writeS16(&reply[2], p.X);
3791         writeS16(&reply[4], p.Y);
3792         writeS16(&reply[6], p.Z);
3793
3794         for(core::map<u16, RemoteClient*>::Iterator
3795                 i = m_clients.getIterator();
3796                 i.atEnd() == false; i++)
3797         {
3798                 // Get client and check that it is valid
3799                 RemoteClient *client = i.getNode()->getValue();
3800                 assert(client->peer_id == i.getNode()->getKey());
3801                 if(client->serialization_version == SER_FMT_VER_INVALID)
3802                         continue;
3803
3804                 // Don't send if it's the same one
3805                 if(client->peer_id == ignore_id)
3806                         continue;
3807                 
3808                 if(far_players)
3809                 {
3810                         // Get player
3811                         Player *player = m_env->getPlayer(client->peer_id);
3812                         if(player)
3813                         {
3814                                 // If player is far away, only set modified blocks not sent
3815                                 v3f player_pos = player->getPosition();
3816                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3817                                 {
3818                                         far_players->push_back(client->peer_id);
3819                                         continue;
3820                                 }
3821                         }
3822                 }
3823
3824                 // Send as reliable
3825                 m_con.Send(client->peer_id, 0, reply, true);
3826         }
3827 }
3828
3829 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3830                 core::list<u16> *far_players, float far_d_nodes)
3831 {
3832         float maxd = far_d_nodes*BS;
3833         v3f p_f = intToFloat(p, BS);
3834
3835         for(core::map<u16, RemoteClient*>::Iterator
3836                 i = m_clients.getIterator();
3837                 i.atEnd() == false; i++)
3838         {
3839                 // Get client and check that it is valid
3840                 RemoteClient *client = i.getNode()->getValue();
3841                 assert(client->peer_id == i.getNode()->getKey());
3842                 if(client->serialization_version == SER_FMT_VER_INVALID)
3843                         continue;
3844
3845                 // Don't send if it's the same one
3846                 if(client->peer_id == ignore_id)
3847                         continue;
3848
3849                 if(far_players)
3850                 {
3851                         // Get player
3852                         Player *player = m_env->getPlayer(client->peer_id);
3853                         if(player)
3854                         {
3855                                 // If player is far away, only set modified blocks not sent
3856                                 v3f player_pos = player->getPosition();
3857                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3858                                 {
3859                                         far_players->push_back(client->peer_id);
3860                                         continue;
3861                                 }
3862                         }
3863                 }
3864
3865                 // Create packet
3866                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
3867                 SharedBuffer<u8> reply(replysize);
3868                 writeU16(&reply[0], TOCLIENT_ADDNODE);
3869                 writeS16(&reply[2], p.X);
3870                 writeS16(&reply[4], p.Y);
3871                 writeS16(&reply[6], p.Z);
3872                 n.serialize(&reply[8], client->serialization_version);
3873
3874                 // Send as reliable
3875                 m_con.Send(client->peer_id, 0, reply, true);
3876         }
3877 }
3878
3879 void Server::setBlockNotSent(v3s16 p)
3880 {
3881         for(core::map<u16, RemoteClient*>::Iterator
3882                 i = m_clients.getIterator();
3883                 i.atEnd()==false; i++)
3884         {
3885                 RemoteClient *client = i.getNode()->getValue();
3886                 client->SetBlockNotSent(p);
3887         }
3888 }
3889
3890 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
3891 {
3892         DSTACK(__FUNCTION_NAME);
3893
3894         v3s16 p = block->getPos();
3895         
3896 #if 0
3897         // Analyze it a bit
3898         bool completely_air = true;
3899         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
3900         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
3901         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
3902         {
3903                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
3904                 {
3905                         completely_air = false;
3906                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
3907                 }
3908         }
3909
3910         // Print result
3911         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
3912         if(completely_air)
3913                 infostream<<"[completely air] ";
3914         infostream<<std::endl;
3915 #endif
3916
3917         /*
3918                 Create a packet with the block in the right format
3919         */
3920         
3921         std::ostringstream os(std::ios_base::binary);
3922         block->serialize(os, ver);
3923         std::string s = os.str();
3924         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
3925
3926         u32 replysize = 8 + blockdata.getSize();
3927         SharedBuffer<u8> reply(replysize);
3928         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
3929         writeS16(&reply[2], p.X);
3930         writeS16(&reply[4], p.Y);
3931         writeS16(&reply[6], p.Z);
3932         memcpy(&reply[8], *blockdata, blockdata.getSize());
3933
3934         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
3935                         <<":  \tpacket size: "<<replysize<<std::endl;*/
3936         
3937         /*
3938                 Send packet
3939         */
3940         m_con.Send(peer_id, 1, reply, true);
3941 }
3942
3943 void Server::SendBlocks(float dtime)
3944 {
3945         DSTACK(__FUNCTION_NAME);
3946
3947         JMutexAutoLock envlock(m_env_mutex);
3948         JMutexAutoLock conlock(m_con_mutex);
3949
3950         //TimeTaker timer("Server::SendBlocks");
3951
3952         core::array<PrioritySortedBlockTransfer> queue;
3953
3954         s32 total_sending = 0;
3955         
3956         {
3957                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
3958
3959                 for(core::map<u16, RemoteClient*>::Iterator
3960                         i = m_clients.getIterator();
3961                         i.atEnd() == false; i++)
3962                 {
3963                         RemoteClient *client = i.getNode()->getValue();
3964                         assert(client->peer_id == i.getNode()->getKey());
3965
3966                         total_sending += client->SendingCount();
3967                         
3968                         if(client->serialization_version == SER_FMT_VER_INVALID)
3969                                 continue;
3970                         
3971                         client->GetNextBlocks(this, dtime, queue);
3972                 }
3973         }
3974
3975         // Sort.
3976         // Lowest priority number comes first.
3977         // Lowest is most important.
3978         queue.sort();
3979
3980         for(u32 i=0; i<queue.size(); i++)
3981         {
3982                 //TODO: Calculate limit dynamically
3983                 if(total_sending >= g_settings->getS32
3984                                 ("max_simultaneous_block_sends_server_total"))
3985                         break;
3986                 
3987                 PrioritySortedBlockTransfer q = queue[i];
3988
3989                 MapBlock *block = NULL;
3990                 try
3991                 {
3992                         block = m_env->getMap().getBlockNoCreate(q.pos);
3993                 }
3994                 catch(InvalidPositionException &e)
3995                 {
3996                         continue;
3997                 }
3998
3999                 RemoteClient *client = getClient(q.peer_id);
4000
4001                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
4002
4003                 client->SentBlock(q.pos);
4004
4005                 total_sending++;
4006         }
4007 }
4008
4009 /*
4010         Something random
4011 */
4012
4013 void Server::HandlePlayerHP(Player *player, s16 damage)
4014 {
4015         if(player->hp > damage)
4016         {
4017                 player->hp -= damage;
4018                 SendPlayerHP(player);
4019         }
4020         else
4021         {
4022                 infostream<<"Server::HandlePlayerHP(): Player "
4023                                 <<player->getName()<<" dies"<<std::endl;
4024                 
4025                 player->hp = 0;
4026                 
4027                 //TODO: Throw items around
4028                 
4029                 // Handle players that are not connected
4030                 if(player->peer_id == PEER_ID_INEXISTENT){
4031                         RespawnPlayer(player);
4032                         return;
4033                 }
4034
4035                 SendPlayerHP(player);
4036                 
4037                 RemoteClient *client = getClient(player->peer_id);
4038                 if(client->net_proto_version >= 3)
4039                 {
4040                         SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
4041                 }
4042                 else
4043                 {
4044                         RespawnPlayer(player);
4045                 }
4046         }
4047 }
4048
4049 void Server::RespawnPlayer(Player *player)
4050 {
4051         v3f pos = findSpawnPos(m_env->getServerMap());
4052         player->setPosition(pos);
4053         player->hp = 20;
4054         SendMovePlayer(player);
4055         SendPlayerHP(player);
4056 }
4057
4058 void Server::UpdateCrafting(u16 peer_id)
4059 {
4060         DSTACK(__FUNCTION_NAME);
4061         
4062         Player* player = m_env->getPlayer(peer_id);
4063         assert(player);
4064
4065         /*
4066                 Calculate crafting stuff
4067         */
4068         if(g_settings->getBool("creative_mode") == false)
4069         {
4070                 InventoryList *clist = player->inventory.getList("craft");
4071                 InventoryList *rlist = player->inventory.getList("craftresult");
4072
4073                 if(rlist && rlist->getUsedSlots() == 0)
4074                         player->craftresult_is_preview = true;
4075
4076                 if(rlist && player->craftresult_is_preview)
4077                 {
4078                         rlist->clearItems();
4079                 }
4080                 if(clist && rlist && player->craftresult_is_preview)
4081                 {
4082                         InventoryItem *items[9];
4083                         for(u16 i=0; i<9; i++)
4084                         {
4085                                 items[i] = clist->getItem(i);
4086                         }
4087                         
4088                         // Get result of crafting grid
4089                         InventoryItem *result = craft_get_result(items);
4090                         if(result)
4091                                 rlist->addItem(result);
4092                 }
4093         
4094         } // if creative_mode == false
4095 }
4096
4097 RemoteClient* Server::getClient(u16 peer_id)
4098 {
4099         DSTACK(__FUNCTION_NAME);
4100         //JMutexAutoLock lock(m_con_mutex);
4101         core::map<u16, RemoteClient*>::Node *n;
4102         n = m_clients.find(peer_id);
4103         // A client should exist for all peers
4104         assert(n != NULL);
4105         return n->getValue();
4106 }
4107
4108 std::wstring Server::getStatusString()
4109 {
4110         std::wostringstream os(std::ios_base::binary);
4111         os<<L"# Server: ";
4112         // Version
4113         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4114         // Uptime
4115         os<<L", uptime="<<m_uptime.get();
4116         // Information about clients
4117         os<<L", clients={";
4118         for(core::map<u16, RemoteClient*>::Iterator
4119                 i = m_clients.getIterator();
4120                 i.atEnd() == false; i++)
4121         {
4122                 // Get client and check that it is valid
4123                 RemoteClient *client = i.getNode()->getValue();
4124                 assert(client->peer_id == i.getNode()->getKey());
4125                 if(client->serialization_version == SER_FMT_VER_INVALID)
4126                         continue;
4127                 // Get player
4128                 Player *player = m_env->getPlayer(client->peer_id);
4129                 // Get name of player
4130                 std::wstring name = L"unknown";
4131                 if(player != NULL)
4132                         name = narrow_to_wide(player->getName());
4133                 // Add name to information string
4134                 os<<name<<L",";
4135         }
4136         os<<L"}";
4137         if(((ServerMap*)(&m_env->getMap()))->isSavingEnabled() == false)
4138                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4139         if(g_settings->get("motd") != "")
4140                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4141         return os.str();
4142 }
4143
4144 // Saves g_settings to configpath given at initialization
4145 void Server::saveConfig()
4146 {
4147         if(m_configpath != "")
4148                 g_settings->updateConfigFile(m_configpath.c_str());
4149 }
4150
4151 void Server::notifyPlayer(const char *name, const std::wstring msg)
4152 {
4153         Player *player = m_env->getPlayer(name);
4154         if(!player)
4155                 return;
4156         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4157 }
4158
4159 void Server::notifyPlayers(const std::wstring msg)
4160 {
4161         BroadcastChatMessage(msg);
4162 }
4163
4164 v3f findSpawnPos(ServerMap &map)
4165 {
4166         //return v3f(50,50,50)*BS;
4167
4168         v3s16 nodepos;
4169         
4170 #if 0
4171         nodepos = v2s16(0,0);
4172         groundheight = 20;
4173 #endif
4174
4175 #if 1
4176         // Try to find a good place a few times
4177         for(s32 i=0; i<1000; i++)
4178         {
4179                 s32 range = 1 + i;
4180                 // We're going to try to throw the player to this position
4181                 v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
4182                                 -range + (myrand()%(range*2)));
4183                 //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
4184                 // Get ground height at point (fallbacks to heightmap function)
4185                 s16 groundheight = map.findGroundLevel(nodepos2d);
4186                 // Don't go underwater
4187                 if(groundheight < WATER_LEVEL)
4188                 {
4189                         //infostream<<"-> Underwater"<<std::endl;
4190                         continue;
4191                 }
4192                 // Don't go to high places
4193                 if(groundheight > WATER_LEVEL + 4)
4194                 {
4195                         //infostream<<"-> Underwater"<<std::endl;
4196                         continue;
4197                 }
4198                 
4199                 nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
4200                 bool is_good = false;
4201                 s32 air_count = 0;
4202                 for(s32 i=0; i<10; i++){
4203                         v3s16 blockpos = getNodeBlockPos(nodepos);
4204                         map.emergeBlock(blockpos, true);
4205                         MapNode n = map.getNodeNoEx(nodepos);
4206                         if(n.getContent() == CONTENT_AIR){
4207                                 air_count++;
4208                                 if(air_count >= 2){
4209                                         is_good = true;
4210                                         nodepos.Y -= 1;
4211                                         break;
4212                                 }
4213                         }
4214                         nodepos.Y++;
4215                 }
4216                 if(is_good){
4217                         // Found a good place
4218                         //infostream<<"Searched through "<<i<<" places."<<std::endl;
4219                         break;
4220                 }
4221         }
4222 #endif
4223         
4224         return intToFloat(nodepos, BS);
4225 }
4226
4227 Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
4228 {
4229         /*
4230                 Try to get an existing player
4231         */
4232         Player *player = m_env->getPlayer(name);
4233         if(player != NULL)
4234         {
4235                 // If player is already connected, cancel
4236                 if(player->peer_id != 0)
4237                 {
4238                         infostream<<"emergePlayer(): Player already connected"<<std::endl;
4239                         return NULL;
4240                 }
4241
4242                 // Got one.
4243                 player->peer_id = peer_id;
4244                 
4245                 // Reset inventory to creative if in creative mode
4246                 if(g_settings->getBool("creative_mode"))
4247                 {
4248                         // Warning: double code below
4249                         // Backup actual inventory
4250                         player->inventory_backup = new Inventory();
4251                         *(player->inventory_backup) = player->inventory;
4252                         // Set creative inventory
4253                         craft_set_creative_inventory(player);
4254                 }
4255
4256                 return player;
4257         }
4258
4259         /*
4260                 If player with the wanted peer_id already exists, cancel.
4261         */
4262         if(m_env->getPlayer(peer_id) != NULL)
4263         {
4264                 infostream<<"emergePlayer(): Player with wrong name but same"
4265                                 " peer_id already exists"<<std::endl;
4266                 return NULL;
4267         }
4268         
4269         /*
4270                 Create a new player
4271         */
4272         {
4273                 player = new ServerRemotePlayer();
4274                 //player->peer_id = c.peer_id;
4275                 //player->peer_id = PEER_ID_INEXISTENT;
4276                 player->peer_id = peer_id;
4277                 player->updateName(name);
4278                 m_authmanager.add(name);
4279                 m_authmanager.setPassword(name, password);
4280                 m_authmanager.setPrivs(name,
4281                                 stringToPrivs(g_settings->get("default_privs")));
4282
4283                 /*
4284                         Set player position
4285                 */
4286                 
4287                 infostream<<"Server: Finding spawn place for player \""
4288                                 <<player->getName()<<"\""<<std::endl;
4289
4290                 v3f pos = findSpawnPos(m_env->getServerMap());
4291
4292                 player->setPosition(pos);
4293
4294                 /*
4295                         Add player to environment
4296                 */
4297
4298                 m_env->addPlayer(player);
4299
4300                 /*
4301                         Add stuff to inventory
4302                 */
4303                 
4304                 if(g_settings->getBool("creative_mode"))
4305                 {
4306                         // Warning: double code above
4307                         // Backup actual inventory
4308                         player->inventory_backup = new Inventory();
4309                         *(player->inventory_backup) = player->inventory;
4310                         // Set creative inventory
4311                         craft_set_creative_inventory(player);
4312                 }
4313                 else if(g_settings->getBool("give_initial_stuff"))
4314                 {
4315                         craft_give_initial_stuff(player);
4316                 }
4317
4318                 return player;
4319                 
4320         } // create new player
4321 }
4322
4323 void Server::handlePeerChange(PeerChange &c)
4324 {
4325         JMutexAutoLock envlock(m_env_mutex);
4326         JMutexAutoLock conlock(m_con_mutex);
4327         
4328         if(c.type == PEER_ADDED)
4329         {
4330                 /*
4331                         Add
4332                 */
4333
4334                 // Error check
4335                 core::map<u16, RemoteClient*>::Node *n;
4336                 n = m_clients.find(c.peer_id);
4337                 // The client shouldn't already exist
4338                 assert(n == NULL);
4339
4340                 // Create client
4341                 RemoteClient *client = new RemoteClient();
4342                 client->peer_id = c.peer_id;
4343                 m_clients.insert(client->peer_id, client);
4344
4345         } // PEER_ADDED
4346         else if(c.type == PEER_REMOVED)
4347         {
4348                 /*
4349                         Delete
4350                 */
4351
4352                 // Error check
4353                 core::map<u16, RemoteClient*>::Node *n;
4354                 n = m_clients.find(c.peer_id);
4355                 // The client should exist
4356                 assert(n != NULL);
4357                 
4358                 /*
4359                         Mark objects to be not known by the client
4360                 */
4361                 RemoteClient *client = n->getValue();
4362                 // Handle objects
4363                 for(core::map<u16, bool>::Iterator
4364                                 i = client->m_known_objects.getIterator();
4365                                 i.atEnd()==false; i++)
4366                 {
4367                         // Get object
4368                         u16 id = i.getNode()->getKey();
4369                         ServerActiveObject* obj = m_env->getActiveObject(id);
4370                         
4371                         if(obj && obj->m_known_by_count > 0)
4372                                 obj->m_known_by_count--;
4373                 }
4374
4375                 // Collect information about leaving in chat
4376                 std::wstring message;
4377                 {
4378                         Player *player = m_env->getPlayer(c.peer_id);
4379                         if(player != NULL)
4380                         {
4381                                 std::wstring name = narrow_to_wide(player->getName());
4382                                 message += L"*** ";
4383                                 message += name;
4384                                 message += L" left game";
4385                                 if(c.timeout)
4386                                         message += L" (timed out)";
4387                         }
4388                 }
4389
4390                 /*// Delete player
4391                 {
4392                         m_env->removePlayer(c.peer_id);
4393                 }*/
4394
4395                 // Set player client disconnected
4396                 {
4397                         Player *player = m_env->getPlayer(c.peer_id);
4398                         if(player != NULL)
4399                                 player->peer_id = 0;
4400                         
4401                         /*
4402                                 Print out action
4403                         */
4404                         if(player != NULL)
4405                         {
4406                                 std::ostringstream os(std::ios_base::binary);
4407                                 for(core::map<u16, RemoteClient*>::Iterator
4408                                         i = m_clients.getIterator();
4409                                         i.atEnd() == false; i++)
4410                                 {
4411                                         RemoteClient *client = i.getNode()->getValue();
4412                                         assert(client->peer_id == i.getNode()->getKey());
4413                                         if(client->serialization_version == SER_FMT_VER_INVALID)
4414                                                 continue;
4415                                         // Get player
4416                                         Player *player = m_env->getPlayer(client->peer_id);
4417                                         if(!player)
4418                                                 continue;
4419                                         // Get name of player
4420                                         os<<player->getName()<<" ";
4421                                 }
4422
4423                                 actionstream<<player->getName()<<" "
4424                                                 <<(c.timeout?"times out.":"leaves game.")
4425                                                 <<" List of players: "
4426                                                 <<os.str()<<std::endl;
4427                         }
4428                 }
4429                 
4430                 // Delete client
4431                 delete m_clients[c.peer_id];
4432                 m_clients.remove(c.peer_id);
4433
4434                 // Send player info to all remaining clients
4435                 SendPlayerInfos();
4436                 
4437                 // Send leave chat message to all remaining clients
4438                 BroadcastChatMessage(message);
4439                 
4440         } // PEER_REMOVED
4441         else
4442         {
4443                 assert(0);
4444         }
4445 }
4446
4447 void Server::handlePeerChanges()
4448 {
4449         while(m_peer_change_queue.size() > 0)
4450         {
4451                 PeerChange c = m_peer_change_queue.pop_front();
4452
4453                 infostream<<"Server: Handling peer change: "
4454                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
4455                                 <<std::endl;
4456
4457                 handlePeerChange(c);
4458         }
4459 }
4460
4461 u64 Server::getPlayerPrivs(Player *player)
4462 {
4463         if(player==NULL)
4464                 return 0;
4465         std::string playername = player->getName();
4466         // Local player gets all privileges regardless of
4467         // what's set on their account.
4468         if(g_settings->get("name") == playername)
4469         {
4470                 return PRIV_ALL;
4471         }
4472         else
4473         {
4474                 return getPlayerAuthPrivs(playername);
4475         }
4476 }
4477
4478 void dedicated_server_loop(Server &server, bool &kill)
4479 {
4480         DSTACK(__FUNCTION_NAME);
4481         
4482         infostream<<DTIME<<std::endl;
4483         infostream<<"========================"<<std::endl;
4484         infostream<<"Running dedicated server"<<std::endl;
4485         infostream<<"========================"<<std::endl;
4486         infostream<<std::endl;
4487
4488         IntervalLimiter m_profiler_interval;
4489
4490         for(;;)
4491         {
4492                 // This is kind of a hack but can be done like this
4493                 // because server.step() is very light
4494                 {
4495                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
4496                         sleep_ms(30);
4497                 }
4498                 server.step(0.030);
4499
4500                 if(server.getShutdownRequested() || kill)
4501                 {
4502                         infostream<<DTIME<<" dedicated_server_loop(): Quitting."<<std::endl;
4503                         break;
4504                 }
4505
4506                 /*
4507                         Profiler
4508                 */
4509                 float profiler_print_interval =
4510                                 g_settings->getFloat("profiler_print_interval");
4511                 if(profiler_print_interval != 0)
4512                 {
4513                         if(m_profiler_interval.step(0.030, profiler_print_interval))
4514                         {
4515                                 infostream<<"Profiler:"<<std::endl;
4516                                 g_profiler->print(infostream);
4517                                 g_profiler->clear();
4518                         }
4519                 }
4520                 
4521                 /*
4522                         Player info
4523                 */
4524                 static int counter = 0;
4525                 counter--;
4526                 if(counter <= 0)
4527                 {
4528                         counter = 10;
4529
4530                         core::list<PlayerInfo> list = server.getPlayerInfo();
4531                         core::list<PlayerInfo>::Iterator i;
4532                         static u32 sum_old = 0;
4533                         u32 sum = PIChecksum(list);
4534                         if(sum != sum_old)
4535                         {
4536                                 infostream<<DTIME<<"Player info:"<<std::endl;
4537                                 for(i=list.begin(); i!=list.end(); i++)
4538                                 {
4539                                         i->PrintLine(&infostream);
4540                                 }
4541                         }
4542                         sum_old = sum;
4543                 }
4544         }
4545 }
4546
4547