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