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 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();
421 bool accessDenied() const { return m_access_denied; }
423 bool reconnectRequested() const { return m_access_denied_reconnect; }
425 void setFatalError(const std::string &reason)
427 m_access_denied = true;
428 m_access_denied_reason = reason;
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; }
435 bool itemdefReceived()
436 { return m_itemdef_received; }
437 bool nodedefReceived()
438 { return m_nodedef_received; }
440 { return m_media_downloader == NULL; }
443 { return m_proto_ver; }
445 bool connectedToServer()
446 { return m_con.Connected(); }
448 float mediaReceiveProgress();
450 void afterContentReceived(IrrlichtDevice *device);
455 Minimap* getMinimap() { return m_minimap; }
456 void setCamera(Camera* camera) { m_camera = camera; }
461 bool shouldShowMinimap() const;
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);
479 virtual std::string getModStoragePath() const;
480 virtual bool registerModStorage(ModMetadata *meta);
481 virtual void unregisterModStorage(const std::string &name);
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);
489 LocalClientState getState() { return m_state; }
491 void makeScreenshot(IrrlichtDevice *device);
493 inline void pushToChatQueue(const std::wstring &input)
495 m_chat_queue.push(input);
498 ClientScripting *getScript() { return m_script; }
499 const bool moddingEnabled() const { return m_modding_enabled; }
501 inline void pushToEventQueue(const ClientEvent &event)
503 m_client_event_queue.push(event);
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);
513 IrrlichtDevice *getDevice() const { return m_device; }
517 // Virtual methods from con::PeerHandler
518 void peerAdded(con::Peer *peer);
519 void deletingPeer(con::Peer *peer, bool timeout);
521 void initLocalMapSaving(const Address &address,
522 const std::string &hostname,
523 bool is_local_server);
528 void sendPlayerPos();
529 // Send the item number 'item' as player item to the server
530 void sendPlayerItem(u16 item);
532 void deleteAuthData();
533 // helper method shared with clientpackethandler
534 static AuthMechanism choseAuthMech(const u32 mechs);
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);
544 inline std::string getPlayerName()
545 { return m_env.getLocalPlayer()->getName(); }
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;
554 IWritableTextureSource *m_tsrc;
555 IWritableShaderSource *m_shsrc;
556 IWritableItemDefManager *m_itemdef;
557 IWritableNodeDefManager *m_nodedef;
558 ISoundManager *m_sound;
559 MtEventManager *m_event;
562 MeshUpdateThread m_mesh_update_thread;
563 ClientEnvironment m_env;
564 ParticleManager m_particle_manager;
565 con::Connection m_con;
566 IrrlichtDevice *m_device;
569 bool m_minimap_disabled_by_server;
570 // Server serialization version
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.
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;
589 // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
591 //u32 m_daynight_ratio;
592 std::queue<std::wstring> m_chat_queue;
594 // The authentication methods we can use to enter sudo mode (=change password)
595 u32 m_sudo_auth_methods;
597 // The seed returned by the server in TOCLIENT_INIT is stored here
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;
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;
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;
623 // An interval for generally sending object positions and stuff
624 float m_recommended_send_interval;
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;
636 UNORDERED_SET<std::string> m_privileges;
638 // Detached inventories
640 UNORDERED_MAP<std::string, Inventory*> m_detached_inventories;
642 // Storage for mesh data for creating multiple instances of the same mesh
643 StringMap m_mesh_data;
646 LocalClientState m_state;
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;
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;
660 DISABLE_CLASS_COPY(Client);
663 #endif // !CLIENT_HEADER