PlayerSAO damage: Update to cope with variable player heights
[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         // cos(angle between velocity and camera) * |velocity|
200         // Limit to 0.0f in case player moves backwards.
201         f32 dot = rangelim(camera_dir.dotProduct(playerspeed), 0.0f, 300.0f);
202
203         // Reduce the field of view when a player moves and looks forward.
204         // limit max fov effect to 50%, 60% at 20n/s fly speed
205         camera_fov = camera_fov / (1 + dot / 300.0f);
206
207         const s16 full_d_max = std::min(m_max_send_distance, wanted_range);
208         const s16 d_opt = std::min(m_block_optimize_distance, wanted_range);
209         const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE;
210         //infostream << "Fov from client " << camera_fov << " full_d_max " << full_d_max << std::endl;
211
212         s16 d_max = full_d_max;
213         s16 d_max_gen = std::min(m_max_gen_distance, wanted_range);
214
215         // Don't loop very much at a time
216         s16 max_d_increment_at_time = 2;
217         if (d_max > d_start + max_d_increment_at_time)
218                 d_max = d_start + max_d_increment_at_time;
219
220         s32 nearest_emerged_d = -1;
221         s32 nearest_emergefull_d = -1;
222         s32 nearest_sent_d = -1;
223         //bool queue_is_full = false;
224
225         const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS);
226
227         s16 d;
228         for (d = d_start; d <= d_max; d++) {
229                 /*
230                         Get the border/face dot coordinates of a "d-radiused"
231                         box
232                 */
233                 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
234
235                 std::vector<v3s16>::iterator li;
236                 for (li = list.begin(); li != list.end(); ++li) {
237                         v3s16 p = *li + center;
238
239                         /*
240                                 Send throttling
241                                 - Don't allow too many simultaneous transfers
242                                 - EXCEPT when the blocks are very close
243
244                                 Also, don't send blocks that are already flying.
245                         */
246
247                         // Start with the usual maximum
248                         u16 max_simul_dynamic = max_simul_sends_usually;
249
250                         // If block is very close, allow full maximum
251                         if (d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
252                                 max_simul_dynamic = m_max_simul_sends;
253
254                         // Don't select too many blocks for sending
255                         if (num_blocks_selected >= max_simul_dynamic) {
256                                 //queue_is_full = true;
257                                 goto queue_full_break;
258                         }
259
260                         // Don't send blocks that are currently being transferred
261                         if (m_blocks_sending.find(p) != m_blocks_sending.end())
262                                 continue;
263
264                         /*
265                                 Do not go over max mapgen limit
266                         */
267                         if (blockpos_over_max_limit(p))
268                                 continue;
269
270                         // If this is true, inexistent block will be made from scratch
271                         bool generate = d <= d_max_gen;
272
273                         /*
274                                 Don't generate or send if not in sight
275                                 FIXME This only works if the client uses a small enough
276                                 FOV setting. The default of 72 degrees is fine.
277                                 Also retrieve a smaller view cone in the direction of the player's
278                                 movement.
279                                 (0.1 is about 4 degrees)
280                         */
281                         f32 dist;
282                         if (!(isBlockInSight(p, camera_pos, camera_dir, camera_fov,
283                                                 d_blocks_in_sight, &dist) ||
284                                         (playerspeed.getLength() > 1.0f * BS &&
285                                         isBlockInSight(p, camera_pos, playerspeeddir, 0.1f,
286                                                 d_blocks_in_sight)))) {
287                                 continue;
288                         }
289
290                         /*
291                                 Don't send already sent blocks
292                         */
293                         if (m_blocks_sent.find(p) != m_blocks_sent.end())
294                                 continue;
295
296                         /*
297                                 Check if map has this block
298                         */
299                         MapBlock *block = env->getMap().getBlockNoCreateNoEx(p);
300
301                         bool surely_not_found_on_disk = false;
302                         bool block_is_invalid = false;
303                         if (block) {
304                                 // Reset usage timer, this block will be of use in the future.
305                                 block->resetUsageTimer();
306
307                                 // Block is dummy if data doesn't exist.
308                                 // It means it has been not found from disk and not generated
309                                 if (block->isDummy()) {
310                                         surely_not_found_on_disk = true;
311                                 }
312
313                                 if (!block->isGenerated())
314                                         block_is_invalid = true;
315
316                                 /*
317                                         If block is not close, don't send it unless it is near
318                                         ground level.
319
320                                         Block is near ground level if night-time mesh
321                                         differs from day-time mesh.
322                                 */
323                                 if (d >= d_opt) {
324                                         if (!block->getDayNightDiff())
325                                                 continue;
326                                 }
327
328                                 if (m_occ_cull && !block_is_invalid &&
329                                                 env->getMap().isBlockOccluded(block, cam_pos_nodes)) {
330                                         continue;
331                                 }
332                         }
333
334                         /*
335                                 If block has been marked to not exist on disk (dummy)
336                                 and generating new ones is not wanted, skip block.
337                         */
338                         if (!generate && surely_not_found_on_disk) {
339                                 // get next one.
340                                 continue;
341                         }
342
343                         /*
344                                 Add inexistent block to emerge queue.
345                         */
346                         if (block == NULL || surely_not_found_on_disk || block_is_invalid) {
347                                 if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
348                                         if (nearest_emerged_d == -1)
349                                                 nearest_emerged_d = d;
350                                 } else {
351                                         if (nearest_emergefull_d == -1)
352                                                 nearest_emergefull_d = d;
353                                         goto queue_full_break;
354                                 }
355
356                                 // get next one.
357                                 continue;
358                         }
359
360                         if (nearest_sent_d == -1)
361                                 nearest_sent_d = d;
362
363                         /*
364                                 Add block to send queue
365                         */
366                         PrioritySortedBlockTransfer q((float)dist, p, peer_id);
367
368                         dest.push_back(q);
369
370                         num_blocks_selected += 1;
371                 }
372         }
373 queue_full_break:
374
375         // If nothing was found for sending and nothing was queued for
376         // emerging, continue next time browsing from here
377         if (nearest_emerged_d != -1) {
378                 new_nearest_unsent_d = nearest_emerged_d;
379         } else if (nearest_emergefull_d != -1) {
380                 new_nearest_unsent_d = nearest_emergefull_d;
381         } else {
382                 if (d > full_d_max) {
383                         new_nearest_unsent_d = 0;
384                         m_nothing_to_send_pause_timer = 2.0f;
385                 } else {
386                         if (nearest_sent_d != -1)
387                                 new_nearest_unsent_d = nearest_sent_d;
388                         else
389                                 new_nearest_unsent_d = d;
390                 }
391         }
392
393         if (new_nearest_unsent_d != -1)
394                 m_nearest_unsent_d = new_nearest_unsent_d;
395 }
396
397 void RemoteClient::GotBlock(v3s16 p)
398 {
399         if (m_blocks_modified.find(p) == m_blocks_modified.end()) {
400                 if (m_blocks_sending.find(p) != m_blocks_sending.end())
401                         m_blocks_sending.erase(p);
402                 else
403                         m_excess_gotblocks++;
404
405                 m_blocks_sent.insert(p);
406         }
407 }
408
409 void RemoteClient::SentBlock(v3s16 p)
410 {
411         if (m_blocks_modified.find(p) != m_blocks_modified.end())
412                 m_blocks_modified.erase(p);
413
414         if (m_blocks_sending.find(p) == m_blocks_sending.end())
415                 m_blocks_sending[p] = 0.0f;
416         else
417                 infostream<<"RemoteClient::SentBlock(): Sent block"
418                                 " already in m_blocks_sending"<<std::endl;
419 }
420
421 void RemoteClient::SetBlockNotSent(v3s16 p)
422 {
423         m_nearest_unsent_d = 0;
424         m_nothing_to_send_pause_timer = 0;
425
426         if (m_blocks_sending.find(p) != m_blocks_sending.end())
427                 m_blocks_sending.erase(p);
428         if (m_blocks_sent.find(p) != m_blocks_sent.end())
429                 m_blocks_sent.erase(p);
430         m_blocks_modified.insert(p);
431 }
432
433 void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
434 {
435         m_nearest_unsent_d = 0;
436         m_nothing_to_send_pause_timer = 0;
437
438         for (auto &block : blocks) {
439                 v3s16 p = block.first;
440                 m_blocks_modified.insert(p);
441
442                 if (m_blocks_sending.find(p) != m_blocks_sending.end())
443                         m_blocks_sending.erase(p);
444                 if (m_blocks_sent.find(p) != m_blocks_sent.end())
445                         m_blocks_sent.erase(p);
446         }
447 }
448
449 void RemoteClient::notifyEvent(ClientStateEvent event)
450 {
451         std::ostringstream myerror;
452         switch (m_state)
453         {
454         case CS_Invalid:
455                 //intentionally do nothing
456                 break;
457         case CS_Created:
458                 switch (event) {
459                 case CSE_Hello:
460                         m_state = CS_HelloSent;
461                         break;
462                 case CSE_InitLegacy:
463                         m_state = CS_AwaitingInit2;
464                         break;
465                 case CSE_Disconnect:
466                         m_state = CS_Disconnecting;
467                         break;
468                 case CSE_SetDenied:
469                         m_state = CS_Denied;
470                         break;
471                 /* GotInit2 SetDefinitionsSent SetMediaSent */
472                 default:
473                         myerror << "Created: Invalid client state transition! " << event;
474                         throw ClientStateError(myerror.str());
475                 }
476                 break;
477         case CS_Denied:
478                 /* don't do anything if in denied state */
479                 break;
480         case CS_HelloSent:
481                 switch(event)
482                 {
483                 case CSE_AuthAccept:
484                         m_state = CS_AwaitingInit2;
485                         if (chosen_mech == AUTH_MECHANISM_SRP ||
486                                         chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
487                                 srp_verifier_delete((SRPVerifier *) auth_data);
488                         chosen_mech = AUTH_MECHANISM_NONE;
489                         break;
490                 case CSE_Disconnect:
491                         m_state = CS_Disconnecting;
492                         break;
493                 case CSE_SetDenied:
494                         m_state = CS_Denied;
495                         if (chosen_mech == AUTH_MECHANISM_SRP ||
496                                         chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
497                                 srp_verifier_delete((SRPVerifier *) auth_data);
498                         chosen_mech = AUTH_MECHANISM_NONE;
499                         break;
500                 default:
501                         myerror << "HelloSent: Invalid client state transition! " << event;
502                         throw ClientStateError(myerror.str());
503                 }
504                 break;
505         case CS_AwaitingInit2:
506                 switch(event)
507                 {
508                 case CSE_GotInit2:
509                         confirmSerializationVersion();
510                         m_state = CS_InitDone;
511                         break;
512                 case CSE_Disconnect:
513                         m_state = CS_Disconnecting;
514                         break;
515                 case CSE_SetDenied:
516                         m_state = CS_Denied;
517                         break;
518
519                 /* Init SetDefinitionsSent SetMediaSent */
520                 default:
521                         myerror << "InitSent: Invalid client state transition! " << event;
522                         throw ClientStateError(myerror.str());
523                 }
524                 break;
525
526         case CS_InitDone:
527                 switch(event)
528                 {
529                 case CSE_SetDefinitionsSent:
530                         m_state = CS_DefinitionsSent;
531                         break;
532                 case CSE_Disconnect:
533                         m_state = CS_Disconnecting;
534                         break;
535                 case CSE_SetDenied:
536                         m_state = CS_Denied;
537                         break;
538
539                 /* Init GotInit2 SetMediaSent */
540                 default:
541                         myerror << "InitDone: Invalid client state transition! " << event;
542                         throw ClientStateError(myerror.str());
543                 }
544                 break;
545         case CS_DefinitionsSent:
546                 switch(event)
547                 {
548                 case CSE_SetClientReady:
549                         m_state = CS_Active;
550                         break;
551                 case CSE_Disconnect:
552                         m_state = CS_Disconnecting;
553                         break;
554                 case CSE_SetDenied:
555                         m_state = CS_Denied;
556                         break;
557                 /* Init GotInit2 SetDefinitionsSent */
558                 default:
559                         myerror << "DefinitionsSent: Invalid client state transition! " << event;
560                         throw ClientStateError(myerror.str());
561                 }
562                 break;
563         case CS_Active:
564                 switch(event)
565                 {
566                 case CSE_SetDenied:
567                         m_state = CS_Denied;
568                         break;
569                 case CSE_Disconnect:
570                         m_state = CS_Disconnecting;
571                         break;
572                 case CSE_SudoSuccess:
573                         m_state = CS_SudoMode;
574                         if (chosen_mech == AUTH_MECHANISM_SRP)
575                                 srp_verifier_delete((SRPVerifier *) auth_data);
576                         chosen_mech = AUTH_MECHANISM_NONE;
577                         break;
578                 /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */
579                 default:
580                         myerror << "Active: Invalid client state transition! " << event;
581                         throw ClientStateError(myerror.str());
582                         break;
583                 }
584                 break;
585         case CS_SudoMode:
586                 switch(event)
587                 {
588                 case CSE_SetDenied:
589                         m_state = CS_Denied;
590                         break;
591                 case CSE_Disconnect:
592                         m_state = CS_Disconnecting;
593                         break;
594                 case CSE_SudoLeave:
595                         m_state = CS_Active;
596                         break;
597                 default:
598                         myerror << "Active: Invalid client state transition! " << event;
599                         throw ClientStateError(myerror.str());
600                         break;
601                 }
602                 break;
603         case CS_Disconnecting:
604                 /* we are already disconnecting */
605                 break;
606         }
607 }
608
609 u64 RemoteClient::uptime() const
610 {
611         return porting::getTimeS() - m_connection_time;
612 }
613
614 ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con)
615 :
616         m_con(con),
617         m_env(NULL),
618         m_print_info_timer(0.0f)
619 {
620
621 }
622 ClientInterface::~ClientInterface()
623 {
624         /*
625                 Delete clients
626         */
627         {
628                 MutexAutoLock clientslock(m_clients_mutex);
629
630                 for (auto &client_it : m_clients) {
631                         // Delete client
632                         delete client_it.second;
633                 }
634         }
635 }
636
637 std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state)
638 {
639         std::vector<session_t> reply;
640         MutexAutoLock clientslock(m_clients_mutex);
641
642         for (const auto &m_client : m_clients) {
643                 if (m_client.second->getState() >= min_state)
644                         reply.push_back(m_client.second->peer_id);
645         }
646
647         return reply;
648 }
649
650 /**
651  * Verify if user limit was reached.
652  * User limit count all clients from HelloSent state (MT protocol user) to Active state
653  * @return true if user limit was reached
654  */
655 bool ClientInterface::isUserLimitReached()
656 {
657         return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users");
658 }
659
660 void ClientInterface::step(float dtime)
661 {
662         m_print_info_timer += dtime;
663         if (m_print_info_timer >= 30.0f) {
664                 m_print_info_timer = 0.0f;
665                 UpdatePlayerList();
666         }
667 }
668
669 void ClientInterface::UpdatePlayerList()
670 {
671         if (m_env) {
672                 std::vector<session_t> clients = getClientIDs();
673                 m_clients_names.clear();
674
675
676                 if (!clients.empty())
677                         infostream<<"Players:"<<std::endl;
678
679                 for (session_t i : clients) {
680                         RemotePlayer *player = m_env->getPlayer(i);
681
682                         if (player == NULL)
683                                 continue;
684
685                         infostream << "* " << player->getName() << "\t";
686
687                         {
688                                 MutexAutoLock clientslock(m_clients_mutex);
689                                 RemoteClient* client = lockedGetClientNoEx(i);
690                                 if (client)
691                                         client->PrintInfo(infostream);
692                         }
693
694                         m_clients_names.emplace_back(player->getName());
695                 }
696         }
697 }
698
699 void ClientInterface::send(session_t peer_id, u8 channelnum,
700                 NetworkPacket *pkt, bool reliable)
701 {
702         m_con->Send(peer_id, channelnum, pkt, reliable);
703 }
704
705 void ClientInterface::sendToAll(NetworkPacket *pkt)
706 {
707         MutexAutoLock clientslock(m_clients_mutex);
708         for (auto &client_it : m_clients) {
709                 RemoteClient *client = client_it.second;
710
711                 if (client->net_proto_version != 0) {
712                         m_con->Send(client->peer_id,
713                                         clientCommandFactoryTable[pkt->getCommand()].channel, pkt,
714                                         clientCommandFactoryTable[pkt->getCommand()].reliable);
715                 }
716         }
717 }
718
719 void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt,
720                 u16 min_proto_ver)
721 {
722         MutexAutoLock clientslock(m_clients_mutex);
723         for (auto &client_it : m_clients) {
724                 RemoteClient *client = client_it.second;
725                 NetworkPacket *pkt_to_send = nullptr;
726
727                 if (client->net_proto_version >= min_proto_ver) {
728                         pkt_to_send = pkt;
729                 } else if (client->net_proto_version != 0) {
730                         pkt_to_send = legacypkt;
731                 } else {
732                         warningstream << "Client with unhandled version to handle: '"
733                                 << client->net_proto_version << "'";
734                         continue;
735                 }
736
737                 m_con->Send(client->peer_id,
738                         clientCommandFactoryTable[pkt_to_send->getCommand()].channel,
739                         pkt_to_send,
740                         clientCommandFactoryTable[pkt_to_send->getCommand()].reliable);
741         }
742 }
743
744 RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min)
745 {
746         MutexAutoLock clientslock(m_clients_mutex);
747         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
748         // The client may not exist; clients are immediately removed if their
749         // access is denied, and this event occurs later then.
750         if (n == m_clients.end())
751                 return NULL;
752
753         if (n->second->getState() >= state_min)
754                 return n->second;
755
756         return NULL;
757 }
758
759 RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min)
760 {
761         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
762         // The client may not exist; clients are immediately removed if their
763         // access is denied, and this event occurs later then.
764         if (n == m_clients.end())
765                 return NULL;
766
767         if (n->second->getState() >= state_min)
768                 return n->second;
769
770         return NULL;
771 }
772
773 ClientState ClientInterface::getClientState(session_t peer_id)
774 {
775         MutexAutoLock clientslock(m_clients_mutex);
776         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
777         // The client may not exist; clients are immediately removed if their
778         // access is denied, and this event occurs later then.
779         if (n == m_clients.end())
780                 return CS_Invalid;
781
782         return n->second->getState();
783 }
784
785 void ClientInterface::setPlayerName(session_t peer_id, const std::string &name)
786 {
787         MutexAutoLock clientslock(m_clients_mutex);
788         RemoteClientMap::iterator n = m_clients.find(peer_id);
789         // The client may not exist; clients are immediately removed if their
790         // access is denied, and this event occurs later then.
791         if (n != m_clients.end())
792                 n->second->setName(name);
793 }
794
795 void ClientInterface::DeleteClient(session_t peer_id)
796 {
797         MutexAutoLock conlock(m_clients_mutex);
798
799         // Error check
800         RemoteClientMap::iterator n = m_clients.find(peer_id);
801         // The client may not exist; clients are immediately removed if their
802         // access is denied, and this event occurs later then.
803         if (n == m_clients.end())
804                 return;
805
806         /*
807                 Mark objects to be not known by the client
808         */
809         //TODO this should be done by client destructor!!!
810         RemoteClient *client = n->second;
811         // Handle objects
812         for (u16 id : client->m_known_objects) {
813                 // Get object
814                 ServerActiveObject* obj = m_env->getActiveObject(id);
815
816                 if(obj && obj->m_known_by_count > 0)
817                         obj->m_known_by_count--;
818         }
819
820         // Delete client
821         delete m_clients[peer_id];
822         m_clients.erase(peer_id);
823 }
824
825 void ClientInterface::CreateClient(session_t peer_id)
826 {
827         MutexAutoLock conlock(m_clients_mutex);
828
829         // Error check
830         RemoteClientMap::iterator n = m_clients.find(peer_id);
831         // The client shouldn't already exist
832         if (n != m_clients.end()) return;
833
834         // Create client
835         RemoteClient *client = new RemoteClient();
836         client->peer_id = peer_id;
837         m_clients[client->peer_id] = client;
838 }
839
840 void ClientInterface::event(session_t peer_id, ClientStateEvent event)
841 {
842         {
843                 MutexAutoLock clientlock(m_clients_mutex);
844
845                 // Error check
846                 RemoteClientMap::iterator n = m_clients.find(peer_id);
847
848                 // No client to deliver event
849                 if (n == m_clients.end())
850                         return;
851                 n->second->notifyEvent(event);
852         }
853
854         if ((event == CSE_SetClientReady) ||
855                 (event == CSE_Disconnect)     ||
856                 (event == CSE_SetDenied))
857         {
858                 UpdatePlayerList();
859         }
860 }
861
862 u16 ClientInterface::getProtocolVersion(session_t peer_id)
863 {
864         MutexAutoLock conlock(m_clients_mutex);
865
866         // Error check
867         RemoteClientMap::iterator n = m_clients.find(peer_id);
868
869         // No client to get version
870         if (n == m_clients.end())
871                 return 0;
872
873         return n->second->net_proto_version;
874 }
875
876 void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch,
877                 const std::string &full)
878 {
879         MutexAutoLock conlock(m_clients_mutex);
880
881         // Error check
882         RemoteClientMap::iterator n = m_clients.find(peer_id);
883
884         // No client to set versions
885         if (n == m_clients.end())
886                 return;
887
888         n->second->setVersionInfo(major, minor, patch, full);
889 }