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