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