Set range of blocks to retrieve per roundtrip to 2.
[oweals/minetest.git] / src / clientiface.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2014 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 <sstream>
21 #include "clientiface.h"
22 #include "network/connection.h"
23 #include "network/serveropcodes.h"
24 #include "remoteplayer.h"
25 #include "settings.h"
26 #include "mapblock.h"
27 #include "serverenvironment.h"
28 #include "map.h"
29 #include "emerge.h"
30 #include "content_sao.h"              // TODO this is used for cleanup of only
31 #include "log.h"
32 #include "util/srp.h"
33 #include "face_position_cache.h"
34
35 const char *ClientInterface::statenames[] = {
36         "Invalid",
37         "Disconnecting",
38         "Denied",
39         "Created",
40         "AwaitingInit2",
41         "HelloSent",
42         "InitDone",
43         "DefinitionsSent",
44         "Active",
45         "SudoMode",
46 };
47
48
49
50 std::string ClientInterface::state2Name(ClientState state)
51 {
52         return statenames[state];
53 }
54
55 RemoteClient::RemoteClient() :
56         m_max_simul_sends(g_settings->getU16("max_simultaneous_block_sends_per_client")),
57         m_min_time_from_building(
58                 g_settings->getFloat("full_block_send_enable_min_time_from_building")),
59         m_max_send_distance(g_settings->getS16("max_block_send_distance")),
60         m_block_optimize_distance(g_settings->getS16("block_send_optimize_distance")),
61         m_max_gen_distance(g_settings->getS16("max_block_generate_distance")),
62         m_occ_cull(g_settings->getBool("server_side_occlusion_culling"))
63 {
64 }
65
66 void RemoteClient::ResendBlockIfOnWire(v3s16 p)
67 {
68         // if this block is on wire, mark it for sending again as soon as possible
69         if (m_blocks_sending.find(p) != m_blocks_sending.end()) {
70                 SetBlockNotSent(p);
71         }
72 }
73
74 LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env)
75 {
76         if (!sao->isAttached())
77                 return nullptr;
78
79         int id;
80         std::string bone;
81         v3f dummy;
82         sao->getAttachment(&id, &bone, &dummy, &dummy);
83         ServerActiveObject *ao = env->getActiveObject(id);
84         while (id && ao) {
85                 ao->getAttachment(&id, &bone, &dummy, &dummy);
86                 if (id)
87                         ao = env->getActiveObject(id);
88         }
89         return dynamic_cast<LuaEntitySAO *>(ao);
90 }
91
92 void RemoteClient::GetNextBlocks (
93                 ServerEnvironment *env,
94                 EmergeManager * emerge,
95                 float dtime,
96                 std::vector<PrioritySortedBlockTransfer> &dest)
97 {
98         // Increment timers
99         m_nothing_to_send_pause_timer -= dtime;
100         m_nearest_unsent_reset_timer += dtime;
101
102         if (m_nothing_to_send_pause_timer >= 0)
103                 return;
104
105         RemotePlayer *player = env->getPlayer(peer_id);
106         // This can happen sometimes; clients and players are not in perfect sync.
107         if (!player)
108                 return;
109
110         PlayerSAO *sao = player->getPlayerSAO();
111         if (!sao)
112                 return;
113
114         // Won't send anything if already sending
115         if (m_blocks_sending.size() >= m_max_simul_sends) {
116                 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
117                 return;
118         }
119
120         v3f playerpos = sao->getBasePosition();
121         // if the player is attached, get the velocity from the attached object
122         LuaEntitySAO *lsao = getAttachedObject(sao, env);
123         const v3f &playerspeed = lsao? lsao->getVelocity() : player->getSpeed();
124         v3f playerspeeddir(0,0,0);
125         if (playerspeed.getLength() > 1.0f * BS)
126                 playerspeeddir = playerspeed / playerspeed.getLength();
127         // Predict to next block
128         v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS;
129
130         v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
131
132         v3s16 center = getNodeBlockPos(center_nodepos);
133
134         // Camera position and direction
135         v3f camera_pos = sao->getEyePosition();
136         v3f camera_dir = v3f(0,0,1);
137         camera_dir.rotateYZBy(sao->getPitch());
138         camera_dir.rotateXZBy(sao->getYaw());
139
140         /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
141                         <<camera_dir.Z<<")"<<std::endl;*/
142
143         /*
144                 Get the starting value of the block finder radius.
145         */
146
147         if (m_last_center != center) {
148                 m_nearest_unsent_d = 0;
149                 m_last_center = center;
150         }
151
152         /*infostream<<"m_nearest_unsent_reset_timer="
153                         <<m_nearest_unsent_reset_timer<<std::endl;*/
154
155         // Reset periodically to workaround for some bugs or stuff
156         if (m_nearest_unsent_reset_timer > 20.0f) {
157                 m_nearest_unsent_reset_timer = 0.0f;
158                 m_nearest_unsent_d = 0;
159                 //infostream<<"Resetting m_nearest_unsent_d for "
160                 //              <<server->getPlayerName(peer_id)<<std::endl;
161         }
162
163         //s16 last_nearest_unsent_d = m_nearest_unsent_d;
164         s16 d_start = m_nearest_unsent_d;
165
166         //infostream<<"d_start="<<d_start<<std::endl;
167
168         u16 max_simul_sends_usually = m_max_simul_sends;
169
170         /*
171                 Check the time from last addNode/removeNode.
172
173                 Decrease send rate if player is building stuff.
174         */
175         m_time_from_building += dtime;
176         if (m_time_from_building < m_min_time_from_building) {
177                 max_simul_sends_usually
178                         = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
179         }
180
181         /*
182                 Number of blocks sending + number of blocks selected for sending
183         */
184         u32 num_blocks_selected = m_blocks_sending.size();
185
186         /*
187                 next time d will be continued from the d from which the nearest
188                 unsent block was found this time.
189
190                 This is because not necessarily any of the blocks found this
191                 time are actually sent.
192         */
193         s32 new_nearest_unsent_d = -1;
194
195         // get view range and camera fov from the client
196         s16 wanted_range = sao->getWantedRange() + 1;
197         float camera_fov = sao->getFov();
198
199         const s16 full_d_max = std::min(m_max_send_distance, wanted_range);
200         const s16 d_opt = std::min(m_block_optimize_distance, wanted_range);
201         const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE;
202         //infostream << "Fov from client " << camera_fov << " full_d_max " << full_d_max << std::endl;
203
204         s16 d_max = full_d_max;
205         s16 d_max_gen = std::min(m_max_gen_distance, wanted_range);
206
207         // Don't loop very much at a time
208         s16 max_d_increment_at_time = 2;
209         if (d_max > d_start + max_d_increment_at_time)
210                 d_max = d_start + max_d_increment_at_time;
211
212         s32 nearest_emerged_d = -1;
213         s32 nearest_emergefull_d = -1;
214         s32 nearest_sent_d = -1;
215         //bool queue_is_full = false;
216
217         const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS);
218
219         s16 d;
220         for (d = d_start; d <= d_max; d++) {
221                 /*
222                         Get the border/face dot coordinates of a "d-radiused"
223                         box
224                 */
225                 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
226
227                 std::vector<v3s16>::iterator li;
228                 for (li = list.begin(); li != list.end(); ++li) {
229                         v3s16 p = *li + center;
230
231                         /*
232                                 Send throttling
233                                 - Don't allow too many simultaneous transfers
234                                 - EXCEPT when the blocks are very close
235
236                                 Also, don't send blocks that are already flying.
237                         */
238
239                         // Start with the usual maximum
240                         u16 max_simul_dynamic = max_simul_sends_usually;
241
242                         // If block is very close, allow full maximum
243                         if (d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
244                                 max_simul_dynamic = m_max_simul_sends;
245
246                         // Don't select too many blocks for sending
247                         if (num_blocks_selected >= max_simul_dynamic) {
248                                 //queue_is_full = true;
249                                 goto queue_full_break;
250                         }
251
252                         // Don't send blocks that are currently being transferred
253                         if (m_blocks_sending.find(p) != m_blocks_sending.end())
254                                 continue;
255
256                         /*
257                                 Do not go over max mapgen limit
258                         */
259                         if (blockpos_over_max_limit(p))
260                                 continue;
261
262                         // If this is true, inexistent block will be made from scratch
263                         bool generate = d <= d_max_gen;
264
265                         /*
266                                 Don't generate or send if not in sight
267                                 FIXME This only works if the client uses a small enough
268                                 FOV setting. The default of 72 degrees is fine.
269                                 Also retrieve a smaller view cone in the direction of the player's
270                                 movement.
271                                 (0.1 is about 4 degrees)
272                         */
273                         f32 dist;
274                         if (!(isBlockInSight(p, camera_pos, camera_dir, camera_fov,
275                                                 d_blocks_in_sight, &dist) ||
276                                         (playerspeed.getLength() > 1.0f * BS &&
277                                         isBlockInSight(p, camera_pos, playerspeeddir, 0.1f,
278                                                 d_blocks_in_sight)))) {
279                                 continue;
280                         }
281
282                         /*
283                                 Don't send already sent blocks
284                         */
285                         if (m_blocks_sent.find(p) != m_blocks_sent.end())
286                                 continue;
287
288                         /*
289                                 Check if map has this block
290                         */
291                         MapBlock *block = env->getMap().getBlockNoCreateNoEx(p);
292
293                         bool surely_not_found_on_disk = false;
294                         bool block_is_invalid = false;
295                         if (block) {
296                                 // Reset usage timer, this block will be of use in the future.
297                                 block->resetUsageTimer();
298
299                                 // Block is dummy if data doesn't exist.
300                                 // It means it has been not found from disk and not generated
301                                 if (block->isDummy()) {
302                                         surely_not_found_on_disk = true;
303                                 }
304
305                                 if (!block->isGenerated())
306                                         block_is_invalid = true;
307
308                                 /*
309                                         If block is not close, don't send it unless it is near
310                                         ground level.
311
312                                         Block is near ground level if night-time mesh
313                                         differs from day-time mesh.
314                                 */
315                                 if (d >= d_opt) {
316                                         if (!block->getDayNightDiff())
317                                                 continue;
318                                 }
319
320                                 if (m_occ_cull && !block_is_invalid &&
321                                                 env->getMap().isBlockOccluded(block, cam_pos_nodes)) {
322                                         continue;
323                                 }
324                         }
325
326                         /*
327                                 If block has been marked to not exist on disk (dummy)
328                                 and generating new ones is not wanted, skip block.
329                         */
330                         if (!generate && surely_not_found_on_disk) {
331                                 // get next one.
332                                 continue;
333                         }
334
335                         /*
336                                 Add inexistent block to emerge queue.
337                         */
338                         if (block == NULL || surely_not_found_on_disk || block_is_invalid) {
339                                 if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
340                                         if (nearest_emerged_d == -1)
341                                                 nearest_emerged_d = d;
342                                 } else {
343                                         if (nearest_emergefull_d == -1)
344                                                 nearest_emergefull_d = d;
345                                         goto queue_full_break;
346                                 }
347
348                                 // get next one.
349                                 continue;
350                         }
351
352                         if (nearest_sent_d == -1)
353                                 nearest_sent_d = d;
354
355                         /*
356                                 Add block to send queue
357                         */
358                         PrioritySortedBlockTransfer q((float)dist, p, peer_id);
359
360                         dest.push_back(q);
361
362                         num_blocks_selected += 1;
363                 }
364         }
365 queue_full_break:
366
367         // If nothing was found for sending and nothing was queued for
368         // emerging, continue next time browsing from here
369         if (nearest_emerged_d != -1) {
370                 new_nearest_unsent_d = nearest_emerged_d;
371         } else if (nearest_emergefull_d != -1) {
372                 new_nearest_unsent_d = nearest_emergefull_d;
373         } else {
374                 if (d > full_d_max) {
375                         new_nearest_unsent_d = 0;
376                         m_nothing_to_send_pause_timer = 2.0f;
377                 } else {
378                         if (nearest_sent_d != -1)
379                                 new_nearest_unsent_d = nearest_sent_d;
380                         else
381                                 new_nearest_unsent_d = d;
382                 }
383         }
384
385         if (new_nearest_unsent_d != -1)
386                 m_nearest_unsent_d = new_nearest_unsent_d;
387 }
388
389 void RemoteClient::GotBlock(v3s16 p)
390 {
391         if (m_blocks_modified.find(p) == m_blocks_modified.end()) {
392                 if (m_blocks_sending.find(p) != m_blocks_sending.end())
393                         m_blocks_sending.erase(p);
394                 else
395                         m_excess_gotblocks++;
396
397                 m_blocks_sent.insert(p);
398         }
399 }
400
401 void RemoteClient::SentBlock(v3s16 p)
402 {
403         if (m_blocks_modified.find(p) != m_blocks_modified.end())
404                 m_blocks_modified.erase(p);
405
406         if (m_blocks_sending.find(p) == m_blocks_sending.end())
407                 m_blocks_sending[p] = 0.0f;
408         else
409                 infostream<<"RemoteClient::SentBlock(): Sent block"
410                                 " already in m_blocks_sending"<<std::endl;
411 }
412
413 void RemoteClient::SetBlockNotSent(v3s16 p)
414 {
415         m_nearest_unsent_d = 0;
416         m_nothing_to_send_pause_timer = 0;
417
418         if (m_blocks_sending.find(p) != m_blocks_sending.end())
419                 m_blocks_sending.erase(p);
420         if (m_blocks_sent.find(p) != m_blocks_sent.end())
421                 m_blocks_sent.erase(p);
422         m_blocks_modified.insert(p);
423 }
424
425 void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
426 {
427         m_nearest_unsent_d = 0;
428         m_nothing_to_send_pause_timer = 0;
429
430         for (auto &block : blocks) {
431                 v3s16 p = block.first;
432                 m_blocks_modified.insert(p);
433
434                 if (m_blocks_sending.find(p) != m_blocks_sending.end())
435                         m_blocks_sending.erase(p);
436                 if (m_blocks_sent.find(p) != m_blocks_sent.end())
437                         m_blocks_sent.erase(p);
438         }
439 }
440
441 void RemoteClient::notifyEvent(ClientStateEvent event)
442 {
443         std::ostringstream myerror;
444         switch (m_state)
445         {
446         case CS_Invalid:
447                 //intentionally do nothing
448                 break;
449         case CS_Created:
450                 switch (event) {
451                 case CSE_Hello:
452                         m_state = CS_HelloSent;
453                         break;
454                 case CSE_InitLegacy:
455                         m_state = CS_AwaitingInit2;
456                         break;
457                 case CSE_Disconnect:
458                         m_state = CS_Disconnecting;
459                         break;
460                 case CSE_SetDenied:
461                         m_state = CS_Denied;
462                         break;
463                 /* GotInit2 SetDefinitionsSent SetMediaSent */
464                 default:
465                         myerror << "Created: Invalid client state transition! " << event;
466                         throw ClientStateError(myerror.str());
467                 }
468                 break;
469         case CS_Denied:
470                 /* don't do anything if in denied state */
471                 break;
472         case CS_HelloSent:
473                 switch(event)
474                 {
475                 case CSE_AuthAccept:
476                         m_state = CS_AwaitingInit2;
477                         if (chosen_mech == AUTH_MECHANISM_SRP ||
478                                         chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
479                                 srp_verifier_delete((SRPVerifier *) auth_data);
480                         chosen_mech = AUTH_MECHANISM_NONE;
481                         break;
482                 case CSE_Disconnect:
483                         m_state = CS_Disconnecting;
484                         break;
485                 case CSE_SetDenied:
486                         m_state = CS_Denied;
487                         if (chosen_mech == AUTH_MECHANISM_SRP ||
488                                         chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
489                                 srp_verifier_delete((SRPVerifier *) auth_data);
490                         chosen_mech = AUTH_MECHANISM_NONE;
491                         break;
492                 default:
493                         myerror << "HelloSent: Invalid client state transition! " << event;
494                         throw ClientStateError(myerror.str());
495                 }
496                 break;
497         case CS_AwaitingInit2:
498                 switch(event)
499                 {
500                 case CSE_GotInit2:
501                         confirmSerializationVersion();
502                         m_state = CS_InitDone;
503                         break;
504                 case CSE_Disconnect:
505                         m_state = CS_Disconnecting;
506                         break;
507                 case CSE_SetDenied:
508                         m_state = CS_Denied;
509                         break;
510
511                 /* Init SetDefinitionsSent SetMediaSent */
512                 default:
513                         myerror << "InitSent: Invalid client state transition! " << event;
514                         throw ClientStateError(myerror.str());
515                 }
516                 break;
517
518         case CS_InitDone:
519                 switch(event)
520                 {
521                 case CSE_SetDefinitionsSent:
522                         m_state = CS_DefinitionsSent;
523                         break;
524                 case CSE_Disconnect:
525                         m_state = CS_Disconnecting;
526                         break;
527                 case CSE_SetDenied:
528                         m_state = CS_Denied;
529                         break;
530
531                 /* Init GotInit2 SetMediaSent */
532                 default:
533                         myerror << "InitDone: Invalid client state transition! " << event;
534                         throw ClientStateError(myerror.str());
535                 }
536                 break;
537         case CS_DefinitionsSent:
538                 switch(event)
539                 {
540                 case CSE_SetClientReady:
541                         m_state = CS_Active;
542                         break;
543                 case CSE_Disconnect:
544                         m_state = CS_Disconnecting;
545                         break;
546                 case CSE_SetDenied:
547                         m_state = CS_Denied;
548                         break;
549                 /* Init GotInit2 SetDefinitionsSent */
550                 default:
551                         myerror << "DefinitionsSent: Invalid client state transition! " << event;
552                         throw ClientStateError(myerror.str());
553                 }
554                 break;
555         case CS_Active:
556                 switch(event)
557                 {
558                 case CSE_SetDenied:
559                         m_state = CS_Denied;
560                         break;
561                 case CSE_Disconnect:
562                         m_state = CS_Disconnecting;
563                         break;
564                 case CSE_SudoSuccess:
565                         m_state = CS_SudoMode;
566                         if (chosen_mech == AUTH_MECHANISM_SRP)
567                                 srp_verifier_delete((SRPVerifier *) auth_data);
568                         chosen_mech = AUTH_MECHANISM_NONE;
569                         break;
570                 /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */
571                 default:
572                         myerror << "Active: Invalid client state transition! " << event;
573                         throw ClientStateError(myerror.str());
574                         break;
575                 }
576                 break;
577         case CS_SudoMode:
578                 switch(event)
579                 {
580                 case CSE_SetDenied:
581                         m_state = CS_Denied;
582                         break;
583                 case CSE_Disconnect:
584                         m_state = CS_Disconnecting;
585                         break;
586                 case CSE_SudoLeave:
587                         m_state = CS_Active;
588                         break;
589                 default:
590                         myerror << "Active: Invalid client state transition! " << event;
591                         throw ClientStateError(myerror.str());
592                         break;
593                 }
594                 break;
595         case CS_Disconnecting:
596                 /* we are already disconnecting */
597                 break;
598         }
599 }
600
601 u64 RemoteClient::uptime() const
602 {
603         return porting::getTimeS() - m_connection_time;
604 }
605
606 ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con)
607 :
608         m_con(con),
609         m_env(NULL),
610         m_print_info_timer(0.0f)
611 {
612
613 }
614 ClientInterface::~ClientInterface()
615 {
616         /*
617                 Delete clients
618         */
619         {
620                 MutexAutoLock clientslock(m_clients_mutex);
621
622                 for (auto &client_it : m_clients) {
623                         // Delete client
624                         delete client_it.second;
625                 }
626         }
627 }
628
629 std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state)
630 {
631         std::vector<session_t> reply;
632         MutexAutoLock clientslock(m_clients_mutex);
633
634         for (const auto &m_client : m_clients) {
635                 if (m_client.second->getState() >= min_state)
636                         reply.push_back(m_client.second->peer_id);
637         }
638
639         return reply;
640 }
641
642 /**
643  * Verify if user limit was reached.
644  * User limit count all clients from HelloSent state (MT protocol user) to Active state
645  * @return true if user limit was reached
646  */
647 bool ClientInterface::isUserLimitReached()
648 {
649         return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users");
650 }
651
652 void ClientInterface::step(float dtime)
653 {
654         m_print_info_timer += dtime;
655         if (m_print_info_timer >= 30.0f) {
656                 m_print_info_timer = 0.0f;
657                 UpdatePlayerList();
658         }
659 }
660
661 void ClientInterface::UpdatePlayerList()
662 {
663         if (m_env) {
664                 std::vector<session_t> clients = getClientIDs();
665                 m_clients_names.clear();
666
667
668                 if (!clients.empty())
669                         infostream<<"Players:"<<std::endl;
670
671                 for (session_t i : clients) {
672                         RemotePlayer *player = m_env->getPlayer(i);
673
674                         if (player == NULL)
675                                 continue;
676
677                         infostream << "* " << player->getName() << "\t";
678
679                         {
680                                 MutexAutoLock clientslock(m_clients_mutex);
681                                 RemoteClient* client = lockedGetClientNoEx(i);
682                                 if (client)
683                                         client->PrintInfo(infostream);
684                         }
685
686                         m_clients_names.emplace_back(player->getName());
687                 }
688         }
689 }
690
691 void ClientInterface::send(session_t peer_id, u8 channelnum,
692                 NetworkPacket *pkt, bool reliable)
693 {
694         m_con->Send(peer_id, channelnum, pkt, reliable);
695 }
696
697 void ClientInterface::sendToAll(NetworkPacket *pkt)
698 {
699         MutexAutoLock clientslock(m_clients_mutex);
700         for (auto &client_it : m_clients) {
701                 RemoteClient *client = client_it.second;
702
703                 if (client->net_proto_version != 0) {
704                         m_con->Send(client->peer_id,
705                                         clientCommandFactoryTable[pkt->getCommand()].channel, pkt,
706                                         clientCommandFactoryTable[pkt->getCommand()].reliable);
707                 }
708         }
709 }
710
711 void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt,
712                 u16 min_proto_ver)
713 {
714         MutexAutoLock clientslock(m_clients_mutex);
715         for (auto &client_it : m_clients) {
716                 RemoteClient *client = client_it.second;
717                 NetworkPacket *pkt_to_send = nullptr;
718
719                 if (client->net_proto_version >= min_proto_ver) {
720                         pkt_to_send = pkt;
721                 } else if (client->net_proto_version != 0) {
722                         pkt_to_send = legacypkt;
723                 } else {
724                         warningstream << "Client with unhandled version to handle: '"
725                                 << client->net_proto_version << "'";
726                         continue;
727                 }
728
729                 m_con->Send(client->peer_id,
730                         clientCommandFactoryTable[pkt_to_send->getCommand()].channel,
731                         pkt_to_send,
732                         clientCommandFactoryTable[pkt_to_send->getCommand()].reliable);
733         }
734 }
735
736 RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min)
737 {
738         MutexAutoLock clientslock(m_clients_mutex);
739         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
740         // The client may not exist; clients are immediately removed if their
741         // access is denied, and this event occurs later then.
742         if (n == m_clients.end())
743                 return NULL;
744
745         if (n->second->getState() >= state_min)
746                 return n->second;
747
748         return NULL;
749 }
750
751 RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min)
752 {
753         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
754         // The client may not exist; clients are immediately removed if their
755         // access is denied, and this event occurs later then.
756         if (n == m_clients.end())
757                 return NULL;
758
759         if (n->second->getState() >= state_min)
760                 return n->second;
761
762         return NULL;
763 }
764
765 ClientState ClientInterface::getClientState(session_t peer_id)
766 {
767         MutexAutoLock clientslock(m_clients_mutex);
768         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
769         // The client may not exist; clients are immediately removed if their
770         // access is denied, and this event occurs later then.
771         if (n == m_clients.end())
772                 return CS_Invalid;
773
774         return n->second->getState();
775 }
776
777 void ClientInterface::setPlayerName(session_t peer_id, const std::string &name)
778 {
779         MutexAutoLock clientslock(m_clients_mutex);
780         RemoteClientMap::iterator n = m_clients.find(peer_id);
781         // The client may not exist; clients are immediately removed if their
782         // access is denied, and this event occurs later then.
783         if (n != m_clients.end())
784                 n->second->setName(name);
785 }
786
787 void ClientInterface::DeleteClient(session_t peer_id)
788 {
789         MutexAutoLock conlock(m_clients_mutex);
790
791         // Error check
792         RemoteClientMap::iterator n = m_clients.find(peer_id);
793         // The client may not exist; clients are immediately removed if their
794         // access is denied, and this event occurs later then.
795         if (n == m_clients.end())
796                 return;
797
798         /*
799                 Mark objects to be not known by the client
800         */
801         //TODO this should be done by client destructor!!!
802         RemoteClient *client = n->second;
803         // Handle objects
804         for (u16 id : client->m_known_objects) {
805                 // Get object
806                 ServerActiveObject* obj = m_env->getActiveObject(id);
807
808                 if(obj && obj->m_known_by_count > 0)
809                         obj->m_known_by_count--;
810         }
811
812         // Delete client
813         delete m_clients[peer_id];
814         m_clients.erase(peer_id);
815 }
816
817 void ClientInterface::CreateClient(session_t peer_id)
818 {
819         MutexAutoLock conlock(m_clients_mutex);
820
821         // Error check
822         RemoteClientMap::iterator n = m_clients.find(peer_id);
823         // The client shouldn't already exist
824         if (n != m_clients.end()) return;
825
826         // Create client
827         RemoteClient *client = new RemoteClient();
828         client->peer_id = peer_id;
829         m_clients[client->peer_id] = client;
830 }
831
832 void ClientInterface::event(session_t peer_id, ClientStateEvent event)
833 {
834         {
835                 MutexAutoLock clientlock(m_clients_mutex);
836
837                 // Error check
838                 RemoteClientMap::iterator n = m_clients.find(peer_id);
839
840                 // No client to deliver event
841                 if (n == m_clients.end())
842                         return;
843                 n->second->notifyEvent(event);
844         }
845
846         if ((event == CSE_SetClientReady) ||
847                 (event == CSE_Disconnect)     ||
848                 (event == CSE_SetDenied))
849         {
850                 UpdatePlayerList();
851         }
852 }
853
854 u16 ClientInterface::getProtocolVersion(session_t peer_id)
855 {
856         MutexAutoLock conlock(m_clients_mutex);
857
858         // Error check
859         RemoteClientMap::iterator n = m_clients.find(peer_id);
860
861         // No client to get version
862         if (n == m_clients.end())
863                 return 0;
864
865         return n->second->net_proto_version;
866 }
867
868 void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch,
869                 const std::string &full)
870 {
871         MutexAutoLock conlock(m_clients_mutex);
872
873         // Error check
874         RemoteClientMap::iterator n = m_clients.find(peer_id);
875
876         // No client to set versions
877         if (n == m_clients.end())
878                 return;
879
880         n->second->setVersionInfo(major, minor, patch, full);
881 }