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,
96 bool set_camera_point_target;
97 f32 camera_point_target_x;
98 f32 camera_point_target_y;
99 f32 camera_point_target_z;
102 std::string *formspec;
103 std::string *formname;
106 //} textures_updated;
113 bool collisiondetection;
114 bool collision_removal;
116 std::string *texture;
117 struct TileAnimationParams animation;
133 bool collisiondetection;
134 bool collision_removal;
137 std::string *texture;
139 struct TileAnimationParams animation;
141 } add_particlespawner;
144 } delete_particlespawner;
173 video::SColor *bgcolor;
175 std::vector<std::string> *params;
180 } override_day_night_ratio;
195 void add(u16 command)
197 std::map<u16, u16>::iterator n = m_packets.find(command);
198 if(n == m_packets.end())
200 m_packets[command] = 1;
210 for(std::map<u16, u16>::iterator
211 i = m_packets.begin();
212 i != m_packets.end(); ++i)
218 void print(std::ostream &o)
220 for(std::map<u16, u16>::iterator
221 i = m_packets.begin();
222 i != m_packets.end(); ++i)
225 <<" count "<<i->second
232 std::map<u16, u16> m_packets;
235 class ClientScripting;
238 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
242 NOTE: Nothing is thread-safe here.
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,
257 GameUIFlags *game_ui_flags
265 request all threads managed by client to be stopped
273 The name of the local player should already be set when
274 calling this, as it is sent in the initialization.
276 void connect(Address address,
277 const std::string &address_name,
278 bool is_local_server);
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
286 void step(float dtime);
292 void handleCommand(NetworkPacket* pkt);
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);
339 void ProcessData(NetworkPacket *pkt);
341 void Send(NetworkPacket* pkt);
343 void interact(u8 action, const PointedThing& pointed);
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);
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();
364 virtual const std::vector<ModSpec> &getMods() const;
365 virtual const ModSpec* getModSpec(const std::string &modname) const;
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);
372 void setPlayerControl(PlayerControl &control);
374 void selectPlayerItem(u16 item);
375 u16 getPlayerItem() const
376 { return m_playeritem; }
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);
384 /* InventoryManager interface */
385 Inventory* getInventory(const InventoryLocation &loc);
386 void inventoryAction(InventoryAction *a);
388 const std::list<std::string> &getConnectedPlayerNames()
390 return m_env.getPlayerNames();
393 float getAnimationTime();
397 void setCrack(int level, v3s16 pos);
401 bool checkPrivilege(const std::string &priv) const
402 { return (m_privileges.count(priv) != 0); }
404 bool getChatMessage(std::wstring &message);
405 void typeChatMessage(const std::wstring& message);
407 u64 getMapSeed(){ return m_map_seed; }
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);
414 void updateCameraOffset(v3s16 camera_offset)
415 { m_mesh_update_thread.m_camera_offset = camera_offset; }
417 // Get event from queue. CE_NONE is returned if queue is empty.
418 ClientEvent getClientEvent();
420 bool accessDenied() const { return m_access_denied; }
422 bool reconnectRequested() const { return m_access_denied_reconnect; }
424 void setFatalError(const std::string &reason)
426 m_access_denied = true;
427 m_access_denied_reason = reason;
430 // Renaming accessDeniedReason to better name could be good as it's used to
431 // disconnect client when CSM failed.
432 const std::string &accessDeniedReason() const { return m_access_denied_reason; }
434 bool itemdefReceived()
435 { return m_itemdef_received; }
436 bool nodedefReceived()
437 { return m_nodedef_received; }
439 { return m_media_downloader == NULL; }
442 { return m_proto_ver; }
444 bool connectedToServer()
445 { return m_con.Connected(); }
447 float mediaReceiveProgress();
449 void afterContentReceived(IrrlichtDevice *device);
454 Minimap* getMinimap() { return m_minimap; }
455 void setCamera(Camera* camera) { m_camera = camera; }
460 bool shouldShowMinimap() const;
462 // IGameDef interface
463 virtual IItemDefManager* getItemDefManager();
464 virtual INodeDefManager* getNodeDefManager();
465 virtual ICraftDefManager* getCraftDefManager();
466 ITextureSource* getTextureSource();
467 virtual IShaderSource* getShaderSource();
468 IShaderSource *shsrc() { return getShaderSource(); }
469 scene::ISceneManager* getSceneManager();
470 virtual u16 allocateUnknownNodeId(const std::string &name);
471 virtual ISoundManager* getSoundManager();
472 virtual MtEventManager* getEventManager();
473 virtual ParticleManager* getParticleManager();
474 bool checkLocalPrivilege(const std::string &priv)
475 { return checkPrivilege(priv); }
476 virtual scene::IAnimatedMesh* getMesh(const std::string &filename);
478 virtual std::string getModStoragePath() const;
479 virtual bool registerModStorage(ModMetadata *meta);
480 virtual void unregisterModStorage(const std::string &name);
482 // The following set of functions is used by ClientMediaDownloader
483 // Insert a media file appropriately into the appropriate manager
484 bool loadMedia(const std::string &data, const std::string &filename);
485 // Send a request for conventional media transfer
486 void request_media(const std::vector<std::string> &file_requests);
488 LocalClientState getState() { return m_state; }
490 void makeScreenshot(IrrlichtDevice *device);
492 inline void pushToChatQueue(const std::wstring &input)
494 m_chat_queue.push(input);
497 ClientScripting *getScript() { return m_script; }
498 const bool moddingEnabled() const { return m_modding_enabled; }
500 inline void pushToEventQueue(const ClientEvent &event)
502 m_client_event_queue.push(event);
505 void showGameChat(const bool show = true);
506 void showGameHud(const bool show = true);
507 void showMinimap(const bool show = true);
508 void showProfiler(const bool show = true);
509 void showGameFog(const bool show = true);
510 void showGameDebug(const bool show = true);
514 // Virtual methods from con::PeerHandler
515 void peerAdded(con::Peer *peer);
516 void deletingPeer(con::Peer *peer, bool timeout);
518 void initLocalMapSaving(const Address &address,
519 const std::string &hostname,
520 bool is_local_server);
525 void sendPlayerPos();
526 // Send the item number 'item' as player item to the server
527 void sendPlayerItem(u16 item);
529 void deleteAuthData();
530 // helper method shared with clientpackethandler
531 static AuthMechanism choseAuthMech(const u32 mechs);
533 void sendLegacyInit(const char* playerName, const char* playerPassword);
534 void sendInit(const std::string &playerName);
535 void startAuth(AuthMechanism chosen_auth_mechanism);
536 void sendDeletedBlocks(std::vector<v3s16> &blocks);
537 void sendGotBlocks(v3s16 block);
538 void sendRemovedSounds(std::vector<s32> &soundList);
541 inline std::string getPlayerName()
542 { return m_env.getLocalPlayer()->getName(); }
544 float m_packetcounter_timer;
545 float m_connection_reinit_timer;
546 float m_avg_rtt_timer;
547 float m_playerpos_send_timer;
548 float m_ignore_damage_timer; // Used after server moves player
549 IntervalLimiter m_map_timer_and_unload_interval;
551 IWritableTextureSource *m_tsrc;
552 IWritableShaderSource *m_shsrc;
553 IWritableItemDefManager *m_itemdef;
554 IWritableNodeDefManager *m_nodedef;
555 ISoundManager *m_sound;
556 MtEventManager *m_event;
559 MeshUpdateThread m_mesh_update_thread;
560 ClientEnvironment m_env;
561 ParticleManager m_particle_manager;
562 con::Connection m_con;
563 IrrlichtDevice *m_device;
566 bool m_minimap_disabled_by_server;
567 // Server serialization version
570 // Used version of the protocol with server
571 // Values smaller than 25 only mean they are smaller than 25,
572 // and aren't accurate. We simply just don't know, because
573 // the server didn't send the version back then.
574 // If 0, server init hasn't been received yet.
578 bool m_inventory_updated;
579 Inventory *m_inventory_from_server;
580 float m_inventory_from_server_age;
581 PacketCounter m_packetcounter;
582 // Block mesh animation parameters
583 float m_animation_time;
586 // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
588 //u32 m_daynight_ratio;
589 std::queue<std::wstring> m_chat_queue;
591 // The authentication methods we can use to enter sudo mode (=change password)
592 u32 m_sudo_auth_methods;
594 // The seed returned by the server in TOCLIENT_INIT is stored here
598 std::string m_playername;
599 std::string m_password;
600 // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
601 std::string m_new_password;
602 // Usable by auth mechanisms.
603 AuthMechanism m_chosen_auth_mech;
607 bool m_access_denied;
608 bool m_access_denied_reconnect;
609 std::string m_access_denied_reason;
610 std::queue<ClientEvent> m_client_event_queue;
611 bool m_itemdef_received;
612 bool m_nodedef_received;
613 ClientMediaDownloader *m_media_downloader;
615 // time_of_day speed approximation for old protocol
616 bool m_time_of_day_set;
617 float m_last_time_of_day_f;
618 float m_time_of_day_update_timer;
620 // An interval for generally sending object positions and stuff
621 float m_recommended_send_interval;
624 float m_removed_sounds_check_timer;
625 // Mapping from server sound ids to our sound ids
626 UNORDERED_MAP<s32, int> m_sounds_server_to_client;
627 // And the other way!
628 UNORDERED_MAP<int, s32> m_sounds_client_to_server;
629 // And relations to objects
630 UNORDERED_MAP<int, u16> m_sounds_to_objects;
633 UNORDERED_SET<std::string> m_privileges;
635 // Detached inventories
637 UNORDERED_MAP<std::string, Inventory*> m_detached_inventories;
639 // Storage for mesh data for creating multiple instances of the same mesh
640 StringMap m_mesh_data;
643 LocalClientState m_state;
645 // Used for saving server map to disk client-side
646 MapDatabase *m_localdb;
647 IntervalLimiter m_localdb_save_interval;
648 u16 m_cache_save_interval;
650 ClientScripting *m_script;
651 bool m_modding_enabled;
652 UNORDERED_MAP<std::string, ModMetadata *> m_mod_storages;
653 float m_mod_storage_save_timer;
654 GameUIFlags *m_game_ui_flags;
657 DISABLE_CLASS_COPY(Client);
660 #endif // !CLIENT_HEADER