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