3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
23 #include "network/connection.h"
24 #include "clientenvironment.h"
25 #include "irrlichttypes_extrabloated.h"
26 #include "threading/mutex.h"
31 #include "clientobject.h"
33 #include "inventorymanager.h"
34 #include "localplayer.h"
36 #include "particles.h"
38 #include "tileanimation.h"
39 #include "mesh_generator_thread.h"
43 class IWritableTextureSource;
44 class IWritableShaderSource;
45 class IWritableItemDefManager;
46 class IWritableNodeDefManager;
47 //class IWritableCraftDefManager;
48 class ClientMediaDownloader;
49 struct MapDrawControl;
54 struct MinimapMapblock;
58 enum LocalClientState {
71 CE_SHOW_LOCAL_FORMSPEC,
73 CE_ADD_PARTICLESPAWNER,
74 CE_DELETE_PARTICLESPAWNER,
79 CE_OVERRIDE_DAY_NIGHT_RATIO,
97 bool set_camera_point_target;
98 f32 camera_point_target_x;
99 f32 camera_point_target_y;
100 f32 camera_point_target_z;
103 std::string *formspec;
104 std::string *formname;
107 //} textures_updated;
114 bool collisiondetection;
115 bool collision_removal;
117 std::string *texture;
118 struct TileAnimationParams animation;
134 bool collisiondetection;
135 bool collision_removal;
138 std::string *texture;
140 struct TileAnimationParams animation;
142 } add_particlespawner;
145 } delete_particlespawner;
174 video::SColor *bgcolor;
176 std::vector<std::string> *params;
182 } override_day_night_ratio;
206 void add(u16 command)
208 std::map<u16, u16>::iterator n = m_packets.find(command);
209 if(n == m_packets.end())
211 m_packets[command] = 1;
221 for(std::map<u16, u16>::iterator
222 i = m_packets.begin();
223 i != m_packets.end(); ++i)
229 void print(std::ostream &o)
231 for(std::map<u16, u16>::iterator
232 i = m_packets.begin();
233 i != m_packets.end(); ++i)
236 <<" count "<<i->second
243 std::map<u16, u16> m_packets;
246 class ClientScripting;
249 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
253 NOTE: Nothing is thread-safe here.
257 IrrlichtDevice *device,
258 const char *playername,
259 const std::string &password,
260 MapDrawControl &control,
261 IWritableTextureSource *tsrc,
262 IWritableShaderSource *shsrc,
263 IWritableItemDefManager *itemdef,
264 IWritableNodeDefManager *nodedef,
265 ISoundManager *sound,
266 MtEventManager *event,
268 GameUIFlags *game_ui_flags
276 request all threads managed by client to be stopped
284 The name of the local player should already be set when
285 calling this, as it is sent in the initialization.
287 void connect(Address address,
288 const std::string &address_name,
289 bool is_local_server);
292 Stuff that references the environment is valid only as
293 long as this is not called. (eg. Players)
294 If this throws a PeerNotFoundException, the connection has
297 void step(float dtime);
303 void handleCommand(NetworkPacket* pkt);
305 void handleCommand_Null(NetworkPacket* pkt) {};
306 void handleCommand_Deprecated(NetworkPacket* pkt);
307 void handleCommand_Hello(NetworkPacket* pkt);
308 void handleCommand_AuthAccept(NetworkPacket* pkt);
309 void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
310 void handleCommand_DenySudoMode(NetworkPacket* pkt);
311 void handleCommand_InitLegacy(NetworkPacket* pkt);
312 void handleCommand_AccessDenied(NetworkPacket* pkt);
313 void handleCommand_RemoveNode(NetworkPacket* pkt);
314 void handleCommand_AddNode(NetworkPacket* pkt);
315 void handleCommand_BlockData(NetworkPacket* pkt);
316 void handleCommand_Inventory(NetworkPacket* pkt);
317 void handleCommand_TimeOfDay(NetworkPacket* pkt);
318 void handleCommand_ChatMessage(NetworkPacket* pkt);
319 void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
320 void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
321 void handleCommand_Movement(NetworkPacket* pkt);
322 void handleCommand_HP(NetworkPacket* pkt);
323 void handleCommand_Breath(NetworkPacket* pkt);
324 void handleCommand_MovePlayer(NetworkPacket* pkt);
325 void handleCommand_DeathScreen(NetworkPacket* pkt);
326 void handleCommand_AnnounceMedia(NetworkPacket* pkt);
327 void handleCommand_Media(NetworkPacket* pkt);
328 void handleCommand_NodeDef(NetworkPacket* pkt);
329 void handleCommand_ItemDef(NetworkPacket* pkt);
330 void handleCommand_PlaySound(NetworkPacket* pkt);
331 void handleCommand_StopSound(NetworkPacket* pkt);
332 void handleCommand_FadeSound(NetworkPacket *pkt);
333 void handleCommand_Privileges(NetworkPacket* pkt);
334 void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
335 void handleCommand_DetachedInventory(NetworkPacket* pkt);
336 void handleCommand_ShowFormSpec(NetworkPacket* pkt);
337 void handleCommand_SpawnParticle(NetworkPacket* pkt);
338 void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
339 void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
340 void handleCommand_HudAdd(NetworkPacket* pkt);
341 void handleCommand_HudRemove(NetworkPacket* pkt);
342 void handleCommand_HudChange(NetworkPacket* pkt);
343 void handleCommand_HudSetFlags(NetworkPacket* pkt);
344 void handleCommand_HudSetParam(NetworkPacket* pkt);
345 void handleCommand_HudSetSky(NetworkPacket* pkt);
346 void handleCommand_CloudParams(NetworkPacket* pkt);
347 void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
348 void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
349 void handleCommand_EyeOffset(NetworkPacket* pkt);
350 void handleCommand_SrpBytesSandB(NetworkPacket* pkt);
352 void ProcessData(NetworkPacket *pkt);
354 void Send(NetworkPacket* pkt);
356 void interact(u8 action, const PointedThing& pointed);
358 void sendNodemetaFields(v3s16 p, const std::string &formname,
359 const StringMap &fields);
360 void sendInventoryFields(const std::string &formname,
361 const StringMap &fields);
362 void sendInventoryAction(InventoryAction *a);
363 void sendChatMessage(const std::wstring &message);
364 void sendChangePassword(const std::string &oldpassword,
365 const std::string &newpassword);
366 void sendDamage(u8 damage);
367 void sendBreath(u16 breath);
371 ClientEnvironment& getEnv() { return m_env; }
372 ITextureSource *tsrc() { return getTextureSource(); }
373 ISoundManager *sound() { return getSoundManager(); }
374 static const std::string &getBuiltinLuaPath();
375 static const std::string &getClientModsLuaPath();
377 virtual const std::vector<ModSpec> &getMods() const;
378 virtual const ModSpec* getModSpec(const std::string &modname) const;
380 // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
381 void removeNode(v3s16 p);
382 MapNode getNode(v3s16 p, bool *is_valid_position);
383 void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
385 void setPlayerControl(PlayerControl &control);
387 void selectPlayerItem(u16 item);
388 u16 getPlayerItem() const
389 { return m_playeritem; }
391 // Returns true if the inventory of the local player has been
392 // updated from the server. If it is true, it is set to false.
393 bool getLocalInventoryUpdated();
394 // Copies the inventory of the local player to parameter
395 void getLocalInventory(Inventory &dst);
397 /* InventoryManager interface */
398 Inventory* getInventory(const InventoryLocation &loc);
399 void inventoryAction(InventoryAction *a);
401 const std::list<std::string> &getConnectedPlayerNames()
403 return m_env.getPlayerNames();
406 float getAnimationTime();
410 void setCrack(int level, v3s16 pos);
414 bool checkPrivilege(const std::string &priv) const
415 { return (m_privileges.count(priv) != 0); }
417 bool getChatMessage(std::wstring &message);
418 void typeChatMessage(const std::wstring& message);
420 u64 getMapSeed(){ return m_map_seed; }
422 void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
423 // Including blocks at appropriate edges
424 void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
425 void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
427 void updateCameraOffset(v3s16 camera_offset)
428 { m_mesh_update_thread.m_camera_offset = camera_offset; }
430 bool hasClientEvents() const { return !m_client_event_queue.empty(); }
431 // Get event from queue. If queue is empty, it triggers an assertion failure.
432 ClientEvent getClientEvent();
434 bool accessDenied() const { return m_access_denied; }
436 bool reconnectRequested() const { return m_access_denied_reconnect; }
438 void setFatalError(const std::string &reason)
440 m_access_denied = true;
441 m_access_denied_reason = reason;
444 // Renaming accessDeniedReason to better name could be good as it's used to
445 // disconnect client when CSM failed.
446 const std::string &accessDeniedReason() const { return m_access_denied_reason; }
448 bool itemdefReceived()
449 { return m_itemdef_received; }
450 bool nodedefReceived()
451 { return m_nodedef_received; }
453 { return m_media_downloader == NULL; }
456 { return m_proto_ver; }
458 bool connectedToServer()
459 { return m_con.Connected(); }
461 float mediaReceiveProgress();
463 void afterContentReceived(IrrlichtDevice *device);
468 Minimap* getMinimap() { return m_minimap; }
469 void setCamera(Camera* camera) { m_camera = camera; }
474 bool shouldShowMinimap() const;
476 // IGameDef interface
477 virtual IItemDefManager* getItemDefManager();
478 virtual INodeDefManager* getNodeDefManager();
479 virtual ICraftDefManager* getCraftDefManager();
480 ITextureSource* getTextureSource();
481 virtual IShaderSource* getShaderSource();
482 IShaderSource *shsrc() { return getShaderSource(); }
483 scene::ISceneManager* getSceneManager();
484 virtual u16 allocateUnknownNodeId(const std::string &name);
485 virtual ISoundManager* getSoundManager();
486 virtual MtEventManager* getEventManager();
487 virtual ParticleManager* getParticleManager();
488 bool checkLocalPrivilege(const std::string &priv)
489 { return checkPrivilege(priv); }
490 virtual scene::IAnimatedMesh* getMesh(const std::string &filename);
492 virtual std::string getModStoragePath() const;
493 virtual bool registerModStorage(ModMetadata *meta);
494 virtual void unregisterModStorage(const std::string &name);
496 // The following set of functions is used by ClientMediaDownloader
497 // Insert a media file appropriately into the appropriate manager
498 bool loadMedia(const std::string &data, const std::string &filename);
499 // Send a request for conventional media transfer
500 void request_media(const std::vector<std::string> &file_requests);
502 LocalClientState getState() { return m_state; }
504 void makeScreenshot(IrrlichtDevice *device);
506 inline void pushToChatQueue(const std::wstring &input)
508 m_chat_queue.push(input);
511 ClientScripting *getScript() { return m_script; }
512 const bool moddingEnabled() const { return m_modding_enabled; }
514 inline void pushToEventQueue(const ClientEvent &event)
516 m_client_event_queue.push(event);
519 void showGameChat(const bool show = true);
520 void showGameHud(const bool show = true);
521 void showMinimap(const bool show = true);
522 void showProfiler(const bool show = true);
523 void showGameFog(const bool show = true);
524 void showGameDebug(const bool show = true);
526 IrrlichtDevice *getDevice() const { return m_device; }
530 // Virtual methods from con::PeerHandler
531 void peerAdded(con::Peer *peer);
532 void deletingPeer(con::Peer *peer, bool timeout);
534 void initLocalMapSaving(const Address &address,
535 const std::string &hostname,
536 bool is_local_server);
541 void sendPlayerPos();
542 // Send the item number 'item' as player item to the server
543 void sendPlayerItem(u16 item);
545 void deleteAuthData();
546 // helper method shared with clientpackethandler
547 static AuthMechanism choseAuthMech(const u32 mechs);
549 void sendLegacyInit(const char* playerName, const char* playerPassword);
550 void sendInit(const std::string &playerName);
551 void startAuth(AuthMechanism chosen_auth_mechanism);
552 void sendDeletedBlocks(std::vector<v3s16> &blocks);
553 void sendGotBlocks(v3s16 block);
554 void sendRemovedSounds(std::vector<s32> &soundList);
557 inline std::string getPlayerName()
558 { return m_env.getLocalPlayer()->getName(); }
560 float m_packetcounter_timer;
561 float m_connection_reinit_timer;
562 float m_avg_rtt_timer;
563 float m_playerpos_send_timer;
564 float m_ignore_damage_timer; // Used after server moves player
565 IntervalLimiter m_map_timer_and_unload_interval;
567 IWritableTextureSource *m_tsrc;
568 IWritableShaderSource *m_shsrc;
569 IWritableItemDefManager *m_itemdef;
570 IWritableNodeDefManager *m_nodedef;
571 ISoundManager *m_sound;
572 MtEventManager *m_event;
575 MeshUpdateThread m_mesh_update_thread;
576 ClientEnvironment m_env;
577 ParticleManager m_particle_manager;
578 con::Connection m_con;
579 IrrlichtDevice *m_device;
582 bool m_minimap_disabled_by_server;
583 // Server serialization version
586 // Used version of the protocol with server
587 // Values smaller than 25 only mean they are smaller than 25,
588 // and aren't accurate. We simply just don't know, because
589 // the server didn't send the version back then.
590 // If 0, server init hasn't been received yet.
594 bool m_inventory_updated;
595 Inventory *m_inventory_from_server;
596 float m_inventory_from_server_age;
597 PacketCounter m_packetcounter;
598 // Block mesh animation parameters
599 float m_animation_time;
602 // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
604 //u32 m_daynight_ratio;
605 std::queue<std::wstring> m_chat_queue;
607 // The authentication methods we can use to enter sudo mode (=change password)
608 u32 m_sudo_auth_methods;
610 // The seed returned by the server in TOCLIENT_INIT is stored here
614 std::string m_playername;
615 std::string m_password;
616 // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
617 std::string m_new_password;
618 // Usable by auth mechanisms.
619 AuthMechanism m_chosen_auth_mech;
623 bool m_access_denied;
624 bool m_access_denied_reconnect;
625 std::string m_access_denied_reason;
626 std::queue<ClientEvent> m_client_event_queue;
627 bool m_itemdef_received;
628 bool m_nodedef_received;
629 ClientMediaDownloader *m_media_downloader;
631 // time_of_day speed approximation for old protocol
632 bool m_time_of_day_set;
633 float m_last_time_of_day_f;
634 float m_time_of_day_update_timer;
636 // An interval for generally sending object positions and stuff
637 float m_recommended_send_interval;
640 float m_removed_sounds_check_timer;
641 // Mapping from server sound ids to our sound ids
642 UNORDERED_MAP<s32, int> m_sounds_server_to_client;
643 // And the other way!
644 UNORDERED_MAP<int, s32> m_sounds_client_to_server;
645 // And relations to objects
646 UNORDERED_MAP<int, u16> m_sounds_to_objects;
649 UNORDERED_SET<std::string> m_privileges;
651 // Detached inventories
653 UNORDERED_MAP<std::string, Inventory*> m_detached_inventories;
655 // Storage for mesh data for creating multiple instances of the same mesh
656 StringMap m_mesh_data;
659 LocalClientState m_state;
661 // Used for saving server map to disk client-side
662 MapDatabase *m_localdb;
663 IntervalLimiter m_localdb_save_interval;
664 u16 m_cache_save_interval;
666 ClientScripting *m_script;
667 bool m_modding_enabled;
668 UNORDERED_MAP<std::string, ModMetadata *> m_mod_storages;
669 float m_mod_storage_save_timer;
670 GameUIFlags *m_game_ui_flags;
673 DISABLE_CLASS_COPY(Client);
676 #endif // !CLIENT_HEADER