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.
21 (c) 2010 Perttu Ahola <celeron55@gmail.com>
27 #include "connection.h"
28 #include "environment.h"
29 #include "common_irrlicht.h"
34 #include "inventory.h"
40 v3f findSpawnPos(ServerMap &map);
43 A structure containing the data needed for queueing the fetching
46 struct QueuedBlockEmerge
49 // key = peer_id, value = flags
50 core::map<u16, u8> peer_ids;
54 This is a thread-safe class.
56 class BlockEmergeQueue
66 JMutexAutoLock lock(m_mutex);
68 core::list<QueuedBlockEmerge*>::Iterator i;
69 for(i=m_queue.begin(); i!=m_queue.end(); i++)
71 QueuedBlockEmerge *q = *i;
77 peer_id=0 adds with nobody to send to
79 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
81 DSTACK(__FUNCTION_NAME);
83 JMutexAutoLock lock(m_mutex);
88 Find if block is already in queue.
89 If it is, update the peer to it and quit.
91 core::list<QueuedBlockEmerge*>::Iterator i;
92 for(i=m_queue.begin(); i!=m_queue.end(); i++)
94 QueuedBlockEmerge *q = *i;
97 q->peer_ids[peer_id] = flags;
106 QueuedBlockEmerge *q = new QueuedBlockEmerge;
109 q->peer_ids[peer_id] = flags;
110 m_queue.push_back(q);
113 // Returned pointer must be deleted
114 // Returns NULL if queue is empty
115 QueuedBlockEmerge * pop()
117 JMutexAutoLock lock(m_mutex);
119 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
120 if(i == m_queue.end())
122 QueuedBlockEmerge *q = *i;
129 JMutexAutoLock lock(m_mutex);
130 return m_queue.size();
133 u32 peerItemCount(u16 peer_id)
135 JMutexAutoLock lock(m_mutex);
139 core::list<QueuedBlockEmerge*>::Iterator i;
140 for(i=m_queue.begin(); i!=m_queue.end(); i++)
142 QueuedBlockEmerge *q = *i;
143 if(q->peer_ids.find(peer_id) != NULL)
151 core::list<QueuedBlockEmerge*> m_queue;
157 class ServerThread : public SimpleThread
163 ServerThread(Server *server):
172 class EmergeThread : public SimpleThread
178 EmergeThread(Server *server):
189 if(IsRunning() == false)
199 char name[PLAYERNAME_SIZE];
205 void PrintLine(std::ostream *s);
208 u32 PIChecksum(core::list<PlayerInfo> &l);
211 Used for queueing and sorting block transfers in containers
213 Lower priority number means higher priority.
215 struct PrioritySortedBlockTransfer
217 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
219 priority = a_priority;
223 bool operator < (PrioritySortedBlockTransfer &other)
225 return priority < other.priority;
235 // peer_id=0 means this client has no associated peer
236 // NOTE: If client is made allowed to exist while peer doesn't,
237 // this has to be set to 0 when there is no peer.
238 // Also, the client must be moved to some other container.
240 // The serialization version to use with the client
241 u8 serialization_version;
242 // Version is stored in here after INIT before INIT2
243 u8 pending_serialization_version;
246 m_time_from_building(9999),
247 m_excess_gotblocks(0)
250 serialization_version = SER_FMT_VER_INVALID;
251 pending_serialization_version = SER_FMT_VER_INVALID;
252 m_nearest_unsent_d = 0;
253 m_nearest_unsent_reset_timer = 0.0;
254 m_nothing_to_send_counter = 0;
255 m_nothing_to_send_pause_timer = 0;
262 Finds block that should be sent next to the client.
263 Environment should be locked when this is called.
264 dtime is used for resetting send radius at slow interval
266 void GetNextBlocks(Server *server, float dtime,
267 core::array<PrioritySortedBlockTransfer> &dest);
270 Connection and environment should be locked when this is called.
271 steps() objects of blocks not found in active_blocks, then
272 adds those blocks to active_blocks
277 core::map<v3s16, bool> &stepped_blocks
280 void GotBlock(v3s16 p);
282 void SentBlock(v3s16 p);
284 void SetBlockNotSent(v3s16 p);
285 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
289 return m_blocks_sending.size();
292 // Increments timeouts and removes timed-out blocks from list
293 // NOTE: This doesn't fix the server-not-sending-block bug
294 // because it is related to emerging, not sending.
295 //void RunSendingTimeouts(float dtime, float timeout);
297 void PrintInfo(std::ostream &o)
299 o<<"RemoteClient "<<peer_id<<": "
300 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
301 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
302 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
303 <<", m_excess_gotblocks="<<m_excess_gotblocks
305 m_excess_gotblocks = 0;
308 // Time from last placing or removing blocks
309 float m_time_from_building;
311 /*JMutex m_dig_mutex;
312 float m_dig_time_remaining;
315 v3s16 m_dig_position;*/
318 List of active objects that the client knows of.
321 core::map<u16, bool> m_known_objects;
325 Blocks that have been sent to client.
326 - These don't have to be sent again.
327 - A block is cleared from here when client says it has
328 deleted it from it's memory
330 Key is position, value is dummy.
331 No MapBlock* is stored here because the blocks can get deleted.
333 core::map<v3s16, bool> m_blocks_sent;
334 s16 m_nearest_unsent_d;
336 float m_nearest_unsent_reset_timer;
339 Blocks that are currently on the line.
340 This is used for throttling the sending of blocks.
341 - The size of this list is limited to some value
342 Block is added when it is sent with BLOCKDATA.
343 Block is removed when GOTBLOCKS is received.
344 Value is time from sending. (not used at the moment)
346 core::map<v3s16, float> m_blocks_sending;
349 Count of excess GotBlocks().
350 There is an excess amount because the client sometimes
351 gets a block so late that the server sends it again,
352 and the client then sends two GOTBLOCKs.
353 This is resetted by PrintInfo()
355 u32 m_excess_gotblocks;
357 // CPU usage optimization
358 u32 m_nothing_to_send_counter;
359 float m_nothing_to_send_pause_timer;
362 class Server : public con::PeerHandler, public MapEventReceiver,
363 public InventoryManager
367 NOTE: Every public method should be thread-safe
371 std::string mapsavedir
374 void start(unsigned short port);
376 // This is mainly a way to pass the time to the server.
377 // Actual processing is done in an another thread.
378 void step(float dtime);
379 // This is run by ServerThread and does the actual processing
382 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
384 core::list<PlayerInfo> getPlayerInfo();
386 /*u32 getDayNightRatio()
388 return time_to_daynight_ratio(m_time_of_day.get());
391 // Environment must be locked when called
392 void setTimeOfDay(u32 time)
394 m_env.setTimeOfDay(time);
395 m_time_of_day_send_timer = 0;
398 bool getShutdownRequested()
400 return m_shutdown_requested;
404 Shall be called with the environment locked.
405 This is accessed by the map, which is inside the environment,
406 so it shouldn't be a problem.
408 void onMapEditEvent(MapEditEvent *event);
411 Shall be called with the environment and the connection locked.
413 Inventory* getInventory(InventoryContext *c, std::string id);
414 void inventoryModified(InventoryContext *c, std::string id);
416 // Connection must be locked when called
417 std::wstring getStatusString();
419 void requestShutdown(void)
421 m_shutdown_requested = true;
425 // Envlock and conlock should be locked when calling this
426 void SendMovePlayer(Player *player);
428 u64 getPlayerAuthPrivs(const std::string &name)
431 return m_authmanager.getPrivs(name);
433 catch(AuthNotFoundException &e)
435 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
440 void setPlayerAuthPrivs(const std::string &name, u64 privs)
443 return m_authmanager.setPrivs(name, privs);
445 catch(AuthNotFoundException &e)
447 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
453 // con::PeerHandler implementation.
454 // These queue stuff to be processed by handlePeerChanges().
455 // As of now, these create and remove clients and players.
456 void peerAdded(con::Peer *peer);
457 void deletingPeer(con::Peer *peer, bool timeout);
463 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
464 static void SendAccessDenied(con::Connection &con, u16 peer_id,
465 const std::wstring &reason);
468 Non-static send methods
471 // Envlock and conlock should be locked when calling these
472 void SendObjectData(float dtime);
473 void SendPlayerInfos();
474 void SendInventory(u16 peer_id);
475 void SendChatMessage(u16 peer_id, const std::wstring &message);
476 void BroadcastChatMessage(const std::wstring &message);
477 void SendPlayerHP(Player *player);
479 Send a node removal/addition event to all clients except ignore_id.
480 Additionally, if far_players!=NULL, players further away than
481 far_d_nodes are ignored and their peer_ids are added to far_players
483 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
484 core::list<u16> *far_players=NULL, float far_d_nodes=100);
485 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
486 core::list<u16> *far_players=NULL, float far_d_nodes=100);
488 // Environment and Connection must be locked when called
489 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
491 // Sends blocks to clients
492 void SendBlocks(float dtime);
498 void UpdateCrafting(u16 peer_id);
500 // When called, connection mutex should be locked
501 RemoteClient* getClient(u16 peer_id);
504 Get a player from memory or creates one.
505 If player is already connected, return NULL
506 The password is not checked here - it is only used to
507 set the password if a new player is created.
509 Call with env and con locked.
511 Player *emergePlayer(const char *name, const char *password, u16 peer_id);
513 // Locks environment and connection by its own
515 void handlePeerChange(PeerChange &c);
516 void handlePeerChanges();
518 u64 getPlayerPrivs(Player *player);
525 float m_liquid_transform_timer;
526 float m_print_info_timer;
527 float m_objectdata_timer;
528 float m_emergethread_trigger_timer;
529 float m_savemap_timer;
531 // NOTE: If connection and environment are both to be locked,
532 // environment shall be locked first.
535 ServerEnvironment m_env;
539 con::Connection m_con;
541 // Connected clients (behind the con mutex)
542 core::map<u16, RemoteClient*> m_clients;
544 // User authentication
545 AuthManager m_authmanager;
551 // A buffer for time steps
552 // step() increments and AsyncRunStep() run by m_thread reads it.
554 JMutex m_step_dtime_mutex;
556 // The server mainly operates in this thread
557 ServerThread m_thread;
558 // This thread fetches and generates map
559 EmergeThread m_emergethread;
560 // Queue of block coordinates to be processed by the emerge thread
561 BlockEmergeQueue m_emerge_queue;
568 //MutexedVariable<u32> m_time_of_day;
569 // Used to buffer dtime for adding to m_time_of_day
570 float m_time_counter;
571 // Timer for sending time of day over network
572 float m_time_of_day_send_timer;
573 // Uptime of server in seconds
574 MutexedVariable<double> m_uptime;
578 Queues stuff from peerAdded() and deletingPeer() to
592 Queue<PeerChange> m_peer_change_queue;
599 std::string m_mapsavedir;
601 bool m_shutdown_requested;
604 Map edit event queue. Automatically receives all map edits.
605 The constructor of this class registers us to receive them through
608 NOTE: Should these be moved to actually be members of
613 Queue of map edits from the environment for sending to the clients
614 This is behind m_env_mutex
616 Queue<MapEditEvent*> m_unsent_map_edit_queue;
618 Set to true when the server itself is modifying the map and does
619 all sending of information by itself.
620 This is behind m_env_mutex
622 bool m_ignore_map_edit_events;
624 If set to !=0, the incoming MapEditEvents are modified to have
625 this peed id as the disabled recipient
626 This is behind m_env_mutex
628 u16 m_ignore_map_edit_events_peer_id;
630 friend class EmergeThread;
631 friend class RemoteClient;
635 Runs a simple dedicated server loop.
637 Shuts down when run is set to false.
639 void dedicated_server_loop(Server &server, bool &run);