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