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