client.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #ifndef CLIENT_HEADER
  17. #define CLIENT_HEADER
  18. #include "network/connection.h"
  19. #include "environment.h"
  20. #include "irrlichttypes_extrabloated.h"
  21. #include "jthread/jmutex.h"
  22. #include <ostream>
  23. #include <map>
  24. #include <set>
  25. #include <vector>
  26. #include "clientobject.h"
  27. #include "gamedef.h"
  28. #include "inventorymanager.h"
  29. #include "localplayer.h"
  30. #include "hud.h"
  31. #include "particles.h"
  32. #include "network/networkpacket.h"
  33. struct MeshMakeData;
  34. class MapBlockMesh;
  35. class IWritableTextureSource;
  36. class IWritableShaderSource;
  37. class IWritableItemDefManager;
  38. class IWritableNodeDefManager;
  39. //class IWritableCraftDefManager;
  40. class ClientMediaDownloader;
  41. struct MapDrawControl;
  42. class MtEventManager;
  43. struct PointedThing;
  44. class Database;
  45. struct QueuedMeshUpdate
  46. {
  47. v3s16 p;
  48. MeshMakeData *data;
  49. bool ack_block_to_server;
  50. QueuedMeshUpdate();
  51. ~QueuedMeshUpdate();
  52. };
  53. enum LocalClientState {
  54. LC_Created,
  55. LC_Init,
  56. LC_Ready
  57. };
  58. /*
  59. A thread-safe queue of mesh update tasks
  60. */
  61. class MeshUpdateQueue
  62. {
  63. public:
  64. MeshUpdateQueue();
  65. ~MeshUpdateQueue();
  66. /*
  67. peer_id=0 adds with nobody to send to
  68. */
  69. void addBlock(v3s16 p, MeshMakeData *data,
  70. bool ack_block_to_server, bool urgent);
  71. // Returned pointer must be deleted
  72. // Returns NULL if queue is empty
  73. QueuedMeshUpdate * pop();
  74. u32 size()
  75. {
  76. JMutexAutoLock lock(m_mutex);
  77. return m_queue.size();
  78. }
  79. private:
  80. std::vector<QueuedMeshUpdate*> m_queue;
  81. std::set<v3s16> m_urgents;
  82. JMutex m_mutex;
  83. };
  84. struct MeshUpdateResult
  85. {
  86. v3s16 p;
  87. MapBlockMesh *mesh;
  88. bool ack_block_to_server;
  89. MeshUpdateResult():
  90. p(-1338,-1338,-1338),
  91. mesh(NULL),
  92. ack_block_to_server(false)
  93. {
  94. }
  95. };
  96. class MeshUpdateThread : public JThread
  97. {
  98. public:
  99. MeshUpdateThread(IGameDef *gamedef):
  100. m_gamedef(gamedef)
  101. {
  102. }
  103. void * Thread();
  104. MeshUpdateQueue m_queue_in;
  105. MutexedQueue<MeshUpdateResult> m_queue_out;
  106. IGameDef *m_gamedef;
  107. v3s16 m_camera_offset;
  108. };
  109. enum ClientEventType
  110. {
  111. CE_NONE,
  112. CE_PLAYER_DAMAGE,
  113. CE_PLAYER_FORCE_MOVE,
  114. CE_DEATHSCREEN,
  115. CE_SHOW_FORMSPEC,
  116. CE_SPAWN_PARTICLE,
  117. CE_ADD_PARTICLESPAWNER,
  118. CE_DELETE_PARTICLESPAWNER,
  119. CE_HUDADD,
  120. CE_HUDRM,
  121. CE_HUDCHANGE,
  122. CE_SET_SKY,
  123. CE_OVERRIDE_DAY_NIGHT_RATIO,
  124. };
  125. struct ClientEvent
  126. {
  127. ClientEventType type;
  128. union{
  129. //struct{
  130. //} none;
  131. struct{
  132. u8 amount;
  133. } player_damage;
  134. struct{
  135. f32 pitch;
  136. f32 yaw;
  137. } player_force_move;
  138. struct{
  139. bool set_camera_point_target;
  140. f32 camera_point_target_x;
  141. f32 camera_point_target_y;
  142. f32 camera_point_target_z;
  143. } deathscreen;
  144. struct{
  145. std::string *formspec;
  146. std::string *formname;
  147. } show_formspec;
  148. //struct{
  149. //} textures_updated;
  150. struct{
  151. v3f *pos;
  152. v3f *vel;
  153. v3f *acc;
  154. f32 expirationtime;
  155. f32 size;
  156. bool collisiondetection;
  157. bool vertical;
  158. std::string *texture;
  159. } spawn_particle;
  160. struct{
  161. u16 amount;
  162. f32 spawntime;
  163. v3f *minpos;
  164. v3f *maxpos;
  165. v3f *minvel;
  166. v3f *maxvel;
  167. v3f *minacc;
  168. v3f *maxacc;
  169. f32 minexptime;
  170. f32 maxexptime;
  171. f32 minsize;
  172. f32 maxsize;
  173. bool collisiondetection;
  174. bool vertical;
  175. std::string *texture;
  176. u32 id;
  177. } add_particlespawner;
  178. struct{
  179. u32 id;
  180. } delete_particlespawner;
  181. struct{
  182. u32 id;
  183. u8 type;
  184. v2f *pos;
  185. std::string *name;
  186. v2f *scale;
  187. std::string *text;
  188. u32 number;
  189. u32 item;
  190. u32 dir;
  191. v2f *align;
  192. v2f *offset;
  193. v3f *world_pos;
  194. v2s32 * size;
  195. } hudadd;
  196. struct{
  197. u32 id;
  198. } hudrm;
  199. struct{
  200. u32 id;
  201. HudElementStat stat;
  202. v2f *v2fdata;
  203. std::string *sdata;
  204. u32 data;
  205. v3f *v3fdata;
  206. v2s32 * v2s32data;
  207. } hudchange;
  208. struct{
  209. video::SColor *bgcolor;
  210. std::string *type;
  211. std::vector<std::string> *params;
  212. } set_sky;
  213. struct{
  214. bool do_override;
  215. float ratio_f;
  216. } override_day_night_ratio;
  217. };
  218. };
  219. /*
  220. Packet counter
  221. */
  222. class PacketCounter
  223. {
  224. public:
  225. PacketCounter()
  226. {
  227. }
  228. void add(u16 command)
  229. {
  230. std::map<u16, u16>::iterator n = m_packets.find(command);
  231. if(n == m_packets.end())
  232. {
  233. m_packets[command] = 1;
  234. }
  235. else
  236. {
  237. n->second++;
  238. }
  239. }
  240. void clear()
  241. {
  242. for(std::map<u16, u16>::iterator
  243. i = m_packets.begin();
  244. i != m_packets.end(); ++i)
  245. {
  246. i->second = 0;
  247. }
  248. }
  249. void print(std::ostream &o)
  250. {
  251. for(std::map<u16, u16>::iterator
  252. i = m_packets.begin();
  253. i != m_packets.end(); ++i)
  254. {
  255. o<<"cmd "<<i->first
  256. <<" count "<<i->second
  257. <<std::endl;
  258. }
  259. }
  260. private:
  261. // command, count
  262. std::map<u16, u16> m_packets;
  263. };
  264. class Client : public con::PeerHandler, public InventoryManager, public IGameDef
  265. {
  266. public:
  267. /*
  268. NOTE: Nothing is thread-safe here.
  269. */
  270. Client(
  271. IrrlichtDevice *device,
  272. const char *playername,
  273. std::string password,
  274. MapDrawControl &control,
  275. IWritableTextureSource *tsrc,
  276. IWritableShaderSource *shsrc,
  277. IWritableItemDefManager *itemdef,
  278. IWritableNodeDefManager *nodedef,
  279. ISoundManager *sound,
  280. MtEventManager *event,
  281. bool ipv6
  282. );
  283. ~Client();
  284. /*
  285. request all threads managed by client to be stopped
  286. */
  287. void Stop();
  288. bool isShutdown();
  289. /*
  290. The name of the local player should already be set when
  291. calling this, as it is sent in the initialization.
  292. */
  293. void connect(Address address,
  294. const std::string &address_name,
  295. bool is_local_server);
  296. /*
  297. Stuff that references the environment is valid only as
  298. long as this is not called. (eg. Players)
  299. If this throws a PeerNotFoundException, the connection has
  300. timed out.
  301. */
  302. void step(float dtime);
  303. /*
  304. * Command Handlers
  305. */
  306. void handleCommand(NetworkPacket* pkt);
  307. void handleCommand_Null(NetworkPacket* pkt) {};
  308. void handleCommand_Deprecated(NetworkPacket* pkt);
  309. void handleCommand_Hello(NetworkPacket* pkt);
  310. void handleCommand_AuthAccept(NetworkPacket* pkt);
  311. void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
  312. void handleCommand_DenySudoMode(NetworkPacket* pkt);
  313. void handleCommand_InitLegacy(NetworkPacket* pkt);
  314. void handleCommand_AccessDenied(NetworkPacket* pkt);
  315. void handleCommand_RemoveNode(NetworkPacket* pkt);
  316. void handleCommand_AddNode(NetworkPacket* pkt);
  317. void handleCommand_BlockData(NetworkPacket* pkt);
  318. void handleCommand_Inventory(NetworkPacket* pkt);
  319. void handleCommand_TimeOfDay(NetworkPacket* pkt);
  320. void handleCommand_ChatMessage(NetworkPacket* pkt);
  321. void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
  322. void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
  323. void handleCommand_Movement(NetworkPacket* pkt);
  324. void handleCommand_HP(NetworkPacket* pkt);
  325. void handleCommand_Breath(NetworkPacket* pkt);
  326. void handleCommand_MovePlayer(NetworkPacket* pkt);
  327. void handleCommand_PlayerItem(NetworkPacket* pkt);
  328. void handleCommand_DeathScreen(NetworkPacket* pkt);
  329. void handleCommand_AnnounceMedia(NetworkPacket* pkt);
  330. void handleCommand_Media(NetworkPacket* pkt);
  331. void handleCommand_ToolDef(NetworkPacket* pkt);
  332. void handleCommand_NodeDef(NetworkPacket* pkt);
  333. void handleCommand_CraftItemDef(NetworkPacket* pkt);
  334. void handleCommand_ItemDef(NetworkPacket* pkt);
  335. void handleCommand_PlaySound(NetworkPacket* pkt);
  336. void handleCommand_StopSound(NetworkPacket* pkt);
  337. void handleCommand_Privileges(NetworkPacket* pkt);
  338. void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
  339. void handleCommand_DetachedInventory(NetworkPacket* pkt);
  340. void handleCommand_ShowFormSpec(NetworkPacket* pkt);
  341. void handleCommand_SpawnParticle(NetworkPacket* pkt);
  342. void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
  343. void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
  344. void handleCommand_HudAdd(NetworkPacket* pkt);
  345. void handleCommand_HudRemove(NetworkPacket* pkt);
  346. void handleCommand_HudChange(NetworkPacket* pkt);
  347. void handleCommand_HudSetFlags(NetworkPacket* pkt);
  348. void handleCommand_HudSetParam(NetworkPacket* pkt);
  349. void handleCommand_HudSetSky(NetworkPacket* pkt);
  350. void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
  351. void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
  352. void handleCommand_EyeOffset(NetworkPacket* pkt);
  353. void handleCommand_SrpBytesSandB(NetworkPacket* pkt);
  354. void ProcessData(NetworkPacket *pkt);
  355. // Returns true if something was received
  356. bool AsyncProcessPacket();
  357. bool AsyncProcessData();
  358. void Send(NetworkPacket* pkt);
  359. void interact(u8 action, const PointedThing& pointed);
  360. void sendNodemetaFields(v3s16 p, const std::string &formname,
  361. const StringMap &fields);
  362. void sendInventoryFields(const std::string &formname,
  363. const StringMap &fields);
  364. void sendInventoryAction(InventoryAction *a);
  365. void sendChatMessage(const std::wstring &message);
  366. void sendChangePassword(const std::string &oldpassword,
  367. const std::string &newpassword);
  368. void sendDamage(u8 damage);
  369. void sendBreath(u16 breath);
  370. void sendRespawn();
  371. void sendReady();
  372. ClientEnvironment& getEnv()
  373. { return m_env; }
  374. // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
  375. void removeNode(v3s16 p);
  376. void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
  377. void setPlayerControl(PlayerControl &control);
  378. void selectPlayerItem(u16 item);
  379. u16 getPlayerItem() const
  380. { return m_playeritem; }
  381. // Returns true if the inventory of the local player has been
  382. // updated from the server. If it is true, it is set to false.
  383. bool getLocalInventoryUpdated();
  384. // Copies the inventory of the local player to parameter
  385. void getLocalInventory(Inventory &dst);
  386. /* InventoryManager interface */
  387. Inventory* getInventory(const InventoryLocation &loc);
  388. void inventoryAction(InventoryAction *a);
  389. // Gets closest object pointed by the shootline
  390. // Returns NULL if not found
  391. ClientActiveObject * getSelectedActiveObject(
  392. f32 max_d,
  393. v3f from_pos_f_on_map,
  394. core::line3d<f32> shootline_on_map
  395. );
  396. std::list<std::string> getConnectedPlayerNames();
  397. float getAnimationTime();
  398. int getCrackLevel();
  399. void setCrack(int level, v3s16 pos);
  400. void setHighlighted(v3s16 pos, bool show_higlighted);
  401. v3s16 getHighlighted(){ return m_highlighted_pos; }
  402. u16 getHP();
  403. u16 getBreath();
  404. bool checkPrivilege(const std::string &priv)
  405. { return (m_privileges.count(priv) != 0); }
  406. bool getChatMessage(std::wstring &message);
  407. void typeChatMessage(const std::wstring& message);
  408. u64 getMapSeed(){ return m_map_seed; }
  409. void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
  410. // Including blocks at appropriate edges
  411. void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
  412. void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
  413. void updateCameraOffset(v3s16 camera_offset)
  414. { m_mesh_update_thread.m_camera_offset = camera_offset; }
  415. // Get event from queue. CE_NONE is returned if queue is empty.
  416. ClientEvent getClientEvent();
  417. bool accessDenied()
  418. { return m_access_denied; }
  419. std::string accessDeniedReason()
  420. { return m_access_denied_reason; }
  421. bool itemdefReceived()
  422. { return m_itemdef_received; }
  423. bool nodedefReceived()
  424. { return m_nodedef_received; }
  425. bool mediaReceived()
  426. { return m_media_downloader == NULL; }
  427. u8 getProtoVersion()
  428. { return m_proto_ver; }
  429. float mediaReceiveProgress();
  430. void afterContentReceived(IrrlichtDevice *device);
  431. float getRTT(void);
  432. float getCurRate(void);
  433. float getAvgRate(void);
  434. // IGameDef interface
  435. virtual IItemDefManager* getItemDefManager();
  436. virtual INodeDefManager* getNodeDefManager();
  437. virtual ICraftDefManager* getCraftDefManager();
  438. virtual ITextureSource* getTextureSource();
  439. virtual IShaderSource* getShaderSource();
  440. virtual scene::ISceneManager* getSceneManager();
  441. virtual u16 allocateUnknownNodeId(const std::string &name);
  442. virtual ISoundManager* getSoundManager();
  443. virtual MtEventManager* getEventManager();
  444. virtual ParticleManager* getParticleManager();
  445. virtual bool checkLocalPrivilege(const std::string &priv)
  446. { return checkPrivilege(priv); }
  447. virtual scene::IAnimatedMesh* getMesh(const std::string &filename);
  448. // The following set of functions is used by ClientMediaDownloader
  449. // Insert a media file appropriately into the appropriate manager
  450. bool loadMedia(const std::string &data, const std::string &filename);
  451. // Send a request for conventional media transfer
  452. void request_media(const std::vector<std::string> &file_requests);
  453. // Send a notification that no conventional media transfer is needed
  454. void received_media();
  455. LocalClientState getState() { return m_state; }
  456. void makeScreenshot(IrrlichtDevice *device);
  457. private:
  458. // Virtual methods from con::PeerHandler
  459. void peerAdded(con::Peer *peer);
  460. void deletingPeer(con::Peer *peer, bool timeout);
  461. void initLocalMapSaving(const Address &address,
  462. const std::string &hostname,
  463. bool is_local_server);
  464. void ReceiveAll();
  465. void Receive();
  466. void sendPlayerPos();
  467. // Send the item number 'item' as player item to the server
  468. void sendPlayerItem(u16 item);
  469. void deleteAuthData();
  470. // helper method shared with clientpackethandler
  471. static AuthMechanism choseAuthMech(const u32 mechs);
  472. void sendLegacyInit(const char* playerName, const char* playerPassword);
  473. void sendInit(const std::string &playerName);
  474. void startAuth(AuthMechanism chosen_auth_mechanism);
  475. void sendDeletedBlocks(std::vector<v3s16> &blocks);
  476. void sendGotBlocks(v3s16 block);
  477. void sendRemovedSounds(std::vector<s32> &soundList);
  478. // Helper function
  479. inline std::string getPlayerName()
  480. { return m_env.getLocalPlayer()->getName(); }
  481. float m_packetcounter_timer;
  482. float m_connection_reinit_timer;
  483. float m_avg_rtt_timer;
  484. float m_playerpos_send_timer;
  485. float m_ignore_damage_timer; // Used after server moves player
  486. IntervalLimiter m_map_timer_and_unload_interval;
  487. IWritableTextureSource *m_tsrc;
  488. IWritableShaderSource *m_shsrc;
  489. IWritableItemDefManager *m_itemdef;
  490. IWritableNodeDefManager *m_nodedef;
  491. ISoundManager *m_sound;
  492. MtEventManager *m_event;
  493. MeshUpdateThread m_mesh_update_thread;
  494. ClientEnvironment m_env;
  495. ParticleManager m_particle_manager;
  496. con::Connection m_con;
  497. IrrlichtDevice *m_device;
  498. // Server serialization version
  499. u8 m_server_ser_ver;
  500. // Used version of the protocol with server
  501. u8 m_proto_ver;
  502. u16 m_playeritem;
  503. bool m_inventory_updated;
  504. Inventory *m_inventory_from_server;
  505. float m_inventory_from_server_age;
  506. PacketCounter m_packetcounter;
  507. bool m_show_highlighted;
  508. // Block mesh animation parameters
  509. float m_animation_time;
  510. int m_crack_level;
  511. v3s16 m_crack_pos;
  512. v3s16 m_highlighted_pos;
  513. // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
  514. //s32 m_daynight_i;
  515. //u32 m_daynight_ratio;
  516. std::queue<std::wstring> m_chat_queue;
  517. // The authentication methods we can use to enter sudo mode (=change password)
  518. u32 m_sudo_auth_methods;
  519. // The seed returned by the server in TOCLIENT_INIT is stored here
  520. u64 m_map_seed;
  521. // Auth data
  522. std::string m_playername;
  523. std::string m_password;
  524. // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
  525. std::string m_new_password;
  526. // Usable by auth mechanisms.
  527. AuthMechanism m_chosen_auth_mech;
  528. void * m_auth_data;
  529. bool m_access_denied;
  530. std::string m_access_denied_reason;
  531. std::queue<ClientEvent> m_client_event_queue;
  532. bool m_itemdef_received;
  533. bool m_nodedef_received;
  534. ClientMediaDownloader *m_media_downloader;
  535. // time_of_day speed approximation for old protocol
  536. bool m_time_of_day_set;
  537. float m_last_time_of_day_f;
  538. float m_time_of_day_update_timer;
  539. // An interval for generally sending object positions and stuff
  540. float m_recommended_send_interval;
  541. // Sounds
  542. float m_removed_sounds_check_timer;
  543. // Mapping from server sound ids to our sound ids
  544. std::map<s32, int> m_sounds_server_to_client;
  545. // And the other way!
  546. std::map<int, s32> m_sounds_client_to_server;
  547. // And relations to objects
  548. std::map<int, u16> m_sounds_to_objects;
  549. // Privileges
  550. std::set<std::string> m_privileges;
  551. // Detached inventories
  552. // key = name
  553. std::map<std::string, Inventory*> m_detached_inventories;
  554. // Storage for mesh data for creating multiple instances of the same mesh
  555. StringMap m_mesh_data;
  556. // own state
  557. LocalClientState m_state;
  558. // Used for saving server map to disk client-side
  559. Database *m_localdb;
  560. IntervalLimiter m_localdb_save_interval;
  561. u16 m_cache_save_interval;
  562. // TODO: Add callback to update these when g_settings changes
  563. bool m_cache_smooth_lighting;
  564. bool m_cache_enable_shaders;
  565. };
  566. #endif // !CLIENT_HEADER