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