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