3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "connection.h"
24 #include "environment.h"
25 #include "common_irrlicht.h"
30 #include "inventory.h"
36 v3f findSpawnPos(ServerMap &map);
39 A structure containing the data needed for queueing the fetching
42 struct QueuedBlockEmerge
45 // key = peer_id, value = flags
46 core::map<u16, u8> peer_ids;
50 This is a thread-safe class.
52 class BlockEmergeQueue
62 JMutexAutoLock lock(m_mutex);
64 core::list<QueuedBlockEmerge*>::Iterator i;
65 for(i=m_queue.begin(); i!=m_queue.end(); i++)
67 QueuedBlockEmerge *q = *i;
73 peer_id=0 adds with nobody to send to
75 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
77 DSTACK(__FUNCTION_NAME);
79 JMutexAutoLock lock(m_mutex);
84 Find if block is already in queue.
85 If it is, update the peer to it and quit.
87 core::list<QueuedBlockEmerge*>::Iterator i;
88 for(i=m_queue.begin(); i!=m_queue.end(); i++)
90 QueuedBlockEmerge *q = *i;
93 q->peer_ids[peer_id] = flags;
102 QueuedBlockEmerge *q = new QueuedBlockEmerge;
105 q->peer_ids[peer_id] = flags;
106 m_queue.push_back(q);
109 // Returned pointer must be deleted
110 // Returns NULL if queue is empty
111 QueuedBlockEmerge * pop()
113 JMutexAutoLock lock(m_mutex);
115 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
116 if(i == m_queue.end())
118 QueuedBlockEmerge *q = *i;
125 JMutexAutoLock lock(m_mutex);
126 return m_queue.size();
129 u32 peerItemCount(u16 peer_id)
131 JMutexAutoLock lock(m_mutex);
135 core::list<QueuedBlockEmerge*>::Iterator i;
136 for(i=m_queue.begin(); i!=m_queue.end(); i++)
138 QueuedBlockEmerge *q = *i;
139 if(q->peer_ids.find(peer_id) != NULL)
147 core::list<QueuedBlockEmerge*> m_queue;
153 class ServerThread : public SimpleThread
159 ServerThread(Server *server):
168 class EmergeThread : public SimpleThread
174 EmergeThread(Server *server):
185 if(IsRunning() == false)
195 char name[PLAYERNAME_SIZE];
201 void PrintLine(std::ostream *s);
204 u32 PIChecksum(core::list<PlayerInfo> &l);
207 Used for queueing and sorting block transfers in containers
209 Lower priority number means higher priority.
211 struct PrioritySortedBlockTransfer
213 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
215 priority = a_priority;
219 bool operator < (PrioritySortedBlockTransfer &other)
221 return priority < other.priority;
231 // peer_id=0 means this client has no associated peer
232 // NOTE: If client is made allowed to exist while peer doesn't,
233 // this has to be set to 0 when there is no peer.
234 // Also, the client must be moved to some other container.
236 // The serialization version to use with the client
237 u8 serialization_version;
238 // Version is stored in here after INIT before INIT2
239 u8 pending_serialization_version;
242 m_time_from_building(9999),
243 m_excess_gotblocks(0)
246 serialization_version = SER_FMT_VER_INVALID;
247 pending_serialization_version = SER_FMT_VER_INVALID;
248 m_nearest_unsent_d = 0;
249 m_nearest_unsent_reset_timer = 0.0;
250 m_nothing_to_send_counter = 0;
251 m_nothing_to_send_pause_timer = 0;
258 Finds block that should be sent next to the client.
259 Environment should be locked when this is called.
260 dtime is used for resetting send radius at slow interval
262 void GetNextBlocks(Server *server, float dtime,
263 core::array<PrioritySortedBlockTransfer> &dest);
266 Connection and environment should be locked when this is called.
267 steps() objects of blocks not found in active_blocks, then
268 adds those blocks to active_blocks
273 core::map<v3s16, bool> &stepped_blocks
276 void GotBlock(v3s16 p);
278 void SentBlock(v3s16 p);
280 void SetBlockNotSent(v3s16 p);
281 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
285 return m_blocks_sending.size();
288 // Increments timeouts and removes timed-out blocks from list
289 // NOTE: This doesn't fix the server-not-sending-block bug
290 // because it is related to emerging, not sending.
291 //void RunSendingTimeouts(float dtime, float timeout);
293 void PrintInfo(std::ostream &o)
295 o<<"RemoteClient "<<peer_id<<": "
296 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
297 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
298 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
299 <<", m_excess_gotblocks="<<m_excess_gotblocks
301 m_excess_gotblocks = 0;
304 // Time from last placing or removing blocks
305 float m_time_from_building;
307 /*JMutex m_dig_mutex;
308 float m_dig_time_remaining;
311 v3s16 m_dig_position;*/
314 List of active objects that the client knows of.
317 core::map<u16, bool> m_known_objects;
321 Blocks that have been sent to client.
322 - These don't have to be sent again.
323 - A block is cleared from here when client says it has
324 deleted it from it's memory
326 Key is position, value is dummy.
327 No MapBlock* is stored here because the blocks can get deleted.
329 core::map<v3s16, bool> m_blocks_sent;
330 s16 m_nearest_unsent_d;
332 float m_nearest_unsent_reset_timer;
335 Blocks that are currently on the line.
336 This is used for throttling the sending of blocks.
337 - The size of this list is limited to some value
338 Block is added when it is sent with BLOCKDATA.
339 Block is removed when GOTBLOCKS is received.
340 Value is time from sending. (not used at the moment)
342 core::map<v3s16, float> m_blocks_sending;
345 Count of excess GotBlocks().
346 There is an excess amount because the client sometimes
347 gets a block so late that the server sends it again,
348 and the client then sends two GOTBLOCKs.
349 This is resetted by PrintInfo()
351 u32 m_excess_gotblocks;
353 // CPU usage optimization
354 u32 m_nothing_to_send_counter;
355 float m_nothing_to_send_pause_timer;
358 class Server : public con::PeerHandler, public MapEventReceiver,
359 public InventoryManager
363 NOTE: Every public method should be thread-safe
367 std::string mapsavedir
370 void start(unsigned short port);
372 // This is mainly a way to pass the time to the server.
373 // Actual processing is done in an another thread.
374 void step(float dtime);
375 // This is run by ServerThread and does the actual processing
378 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
380 core::list<PlayerInfo> getPlayerInfo();
382 /*u32 getDayNightRatio()
384 return time_to_daynight_ratio(m_time_of_day.get());
387 // Environment must be locked when called
388 void setTimeOfDay(u32 time)
390 m_env.setTimeOfDay(time);
391 m_time_of_day_send_timer = 0;
394 bool getShutdownRequested()
396 return m_shutdown_requested;
400 Shall be called with the environment locked.
401 This is accessed by the map, which is inside the environment,
402 so it shouldn't be a problem.
404 void onMapEditEvent(MapEditEvent *event);
407 Shall be called with the environment and the connection locked.
409 Inventory* getInventory(InventoryContext *c, std::string id);
410 void inventoryModified(InventoryContext *c, std::string id);
412 // Connection must be locked when called
413 std::wstring getStatusString();
415 void requestShutdown(void)
417 m_shutdown_requested = true;
421 // Envlock and conlock should be locked when calling this
422 void SendMovePlayer(Player *player);
424 u64 getPlayerAuthPrivs(const std::string &name)
427 return m_authmanager.getPrivs(name);
429 catch(AuthNotFoundException &e)
431 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
436 void setPlayerAuthPrivs(const std::string &name, u64 privs)
439 return m_authmanager.setPrivs(name, privs);
441 catch(AuthNotFoundException &e)
443 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
449 // con::PeerHandler implementation.
450 // These queue stuff to be processed by handlePeerChanges().
451 // As of now, these create and remove clients and players.
452 void peerAdded(con::Peer *peer);
453 void deletingPeer(con::Peer *peer, bool timeout);
459 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
460 static void SendAccessDenied(con::Connection &con, u16 peer_id,
461 const std::wstring &reason);
464 Non-static send methods
467 // Envlock and conlock should be locked when calling these
468 void SendObjectData(float dtime);
469 void SendPlayerInfos();
470 void SendInventory(u16 peer_id);
471 void SendChatMessage(u16 peer_id, const std::wstring &message);
472 void BroadcastChatMessage(const std::wstring &message);
473 void SendPlayerHP(Player *player);
475 Send a node removal/addition event to all clients except ignore_id.
476 Additionally, if far_players!=NULL, players further away than
477 far_d_nodes are ignored and their peer_ids are added to far_players
479 // Envlock and conlock should be locked when calling these
480 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
481 core::list<u16> *far_players=NULL, float far_d_nodes=100);
482 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
483 core::list<u16> *far_players=NULL, float far_d_nodes=100);
484 void setBlockNotSent(v3s16 p);
486 // Environment and Connection must be locked when called
487 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
489 // Sends blocks to clients (locks env and con on its own)
490 void SendBlocks(float dtime);
496 void UpdateCrafting(u16 peer_id);
498 // When called, connection mutex should be locked
499 RemoteClient* getClient(u16 peer_id);
501 // When called, environment mutex should be locked
502 std::string getPlayerName(u16 peer_id)
504 Player *player = m_env.getPlayer(peer_id);
506 return "[id="+itos(peer_id);
507 return player->getName();
511 Get a player from memory or creates one.
512 If player is already connected, return NULL
513 The password is not checked here - it is only used to
514 set the password if a new player is created.
516 Call with env and con locked.
518 Player *emergePlayer(const char *name, const char *password, u16 peer_id);
520 // Locks environment and connection by its own
522 void handlePeerChange(PeerChange &c);
523 void handlePeerChanges();
525 u64 getPlayerPrivs(Player *player);
532 float m_liquid_transform_timer;
533 float m_print_info_timer;
534 float m_objectdata_timer;
535 float m_emergethread_trigger_timer;
536 float m_savemap_timer;
537 IntervalLimiter m_map_timer_and_unload_interval;
539 // NOTE: If connection and environment are both to be locked,
540 // environment shall be locked first.
543 ServerEnvironment m_env;
547 con::Connection m_con;
549 // Connected clients (behind the con mutex)
550 core::map<u16, RemoteClient*> m_clients;
552 // User authentication
553 AuthManager m_authmanager;
559 // A buffer for time steps
560 // step() increments and AsyncRunStep() run by m_thread reads it.
562 JMutex m_step_dtime_mutex;
564 // The server mainly operates in this thread
565 ServerThread m_thread;
566 // This thread fetches and generates map
567 EmergeThread m_emergethread;
568 // Queue of block coordinates to be processed by the emerge thread
569 BlockEmergeQueue m_emerge_queue;
576 //MutexedVariable<u32> m_time_of_day;
577 // Used to buffer dtime for adding to m_time_of_day
578 float m_time_counter;
579 // Timer for sending time of day over network
580 float m_time_of_day_send_timer;
581 // Uptime of server in seconds
582 MutexedVariable<double> m_uptime;
586 Queues stuff from peerAdded() and deletingPeer() to
600 Queue<PeerChange> m_peer_change_queue;
607 std::string m_mapsavedir;
609 bool m_shutdown_requested;
612 Map edit event queue. Automatically receives all map edits.
613 The constructor of this class registers us to receive them through
616 NOTE: Should these be moved to actually be members of
621 Queue of map edits from the environment for sending to the clients
622 This is behind m_env_mutex
624 Queue<MapEditEvent*> m_unsent_map_edit_queue;
626 Set to true when the server itself is modifying the map and does
627 all sending of information by itself.
628 This is behind m_env_mutex
630 bool m_ignore_map_edit_events;
632 If set to !=0, the incoming MapEditEvents are modified to have
633 this peed id as the disabled recipient
634 This is behind m_env_mutex
636 u16 m_ignore_map_edit_events_peer_id;
638 Profiler *m_profiler;
640 friend class EmergeThread;
641 friend class RemoteClient;
645 Runs a simple dedicated server loop.
647 Shuts down when run is set to false.
649 void dedicated_server_loop(Server &server, bool &run);