Merge: New map directory structure and player passwords
[oweals/minetest.git] / src / client.h
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 #ifndef SERVER
24
25 #include "connection.h"
26 #include "environment.h"
27 #include "common_irrlicht.h"
28 #include "jmutex.h"
29 #include <ostream>
30 #include "clientobject.h"
31
32 class ClientNotReadyException : public BaseException
33 {
34 public:
35         ClientNotReadyException(const char *s):
36                 BaseException(s)
37         {}
38 };
39
40 struct QueuedMeshUpdate
41 {
42         v3s16 p;
43         MeshMakeData *data;
44         bool ack_block_to_server;
45
46         QueuedMeshUpdate():
47                 p(-1337,-1337,-1337),
48                 data(NULL),
49                 ack_block_to_server(false)
50         {
51         }
52         
53         ~QueuedMeshUpdate()
54         {
55                 if(data)
56                         delete data;
57         }
58 };
59
60 /*
61         A thread-safe queue of mesh update tasks
62 */
63 class MeshUpdateQueue
64 {
65 public:
66         MeshUpdateQueue()
67         {
68                 m_mutex.Init();
69         }
70
71         ~MeshUpdateQueue()
72         {
73                 JMutexAutoLock lock(m_mutex);
74
75                 core::list<QueuedMeshUpdate*>::Iterator i;
76                 for(i=m_queue.begin(); i!=m_queue.end(); i++)
77                 {
78                         QueuedMeshUpdate *q = *i;
79                         delete q;
80                 }
81         }
82         
83         /*
84                 peer_id=0 adds with nobody to send to
85         */
86         void addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server)
87         {
88                 DSTACK(__FUNCTION_NAME);
89
90                 assert(data);
91         
92                 JMutexAutoLock lock(m_mutex);
93
94                 /*
95                         Find if block is already in queue.
96                         If it is, update the data and quit.
97                 */
98                 core::list<QueuedMeshUpdate*>::Iterator i;
99                 for(i=m_queue.begin(); i!=m_queue.end(); i++)
100                 {
101                         QueuedMeshUpdate *q = *i;
102                         if(q->p == p)
103                         {
104                                 if(q->data)
105                                         delete q->data;
106                                 q->data = data;
107                                 if(ack_block_to_server)
108                                         q->ack_block_to_server = true;
109                                 return;
110                         }
111                 }
112                 
113                 /*
114                         Add the block
115                 */
116                 QueuedMeshUpdate *q = new QueuedMeshUpdate;
117                 q->p = p;
118                 q->data = data;
119                 q->ack_block_to_server = ack_block_to_server;
120                 m_queue.push_back(q);
121         }
122
123         // Returned pointer must be deleted
124         // Returns NULL if queue is empty
125         QueuedMeshUpdate * pop()
126         {
127                 JMutexAutoLock lock(m_mutex);
128
129                 core::list<QueuedMeshUpdate*>::Iterator i = m_queue.begin();
130                 if(i == m_queue.end())
131                         return NULL;
132                 QueuedMeshUpdate *q = *i;
133                 m_queue.erase(i);
134                 return q;
135         }
136
137         u32 size()
138         {
139                 JMutexAutoLock lock(m_mutex);
140                 return m_queue.size();
141         }
142         
143 private:
144         core::list<QueuedMeshUpdate*> m_queue;
145         JMutex m_mutex;
146 };
147
148 struct MeshUpdateResult
149 {
150         v3s16 p;
151         scene::SMesh *mesh;
152         bool ack_block_to_server;
153
154         MeshUpdateResult():
155                 p(-1338,-1338,-1338),
156                 mesh(NULL),
157                 ack_block_to_server(false)
158         {
159         }
160 };
161
162 class MeshUpdateThread : public SimpleThread
163 {
164 public:
165
166         MeshUpdateThread()
167         {
168         }
169
170         void * Thread();
171
172         MeshUpdateQueue m_queue_in;
173
174         MutexedQueue<MeshUpdateResult> m_queue_out;
175 };
176
177 enum ClientEventType
178 {
179         CE_NONE,
180         CE_PLAYER_DAMAGE,
181         CE_PLAYER_FORCE_MOVE
182 };
183
184 struct ClientEvent
185 {
186         ClientEventType type;
187         union{
188                 struct{
189                 } none;
190                 struct{
191                         u8 amount;
192                 } player_damage;
193                 struct{
194                         f32 pitch;
195                         f32 yaw;
196                 } player_force_move;
197         };
198 };
199
200 class Client : public con::PeerHandler, public InventoryManager
201 {
202 public:
203         /*
204                 NOTE: Nothing is thread-safe here.
205         */
206
207         Client(
208                         IrrlichtDevice *device,
209                         const char *playername,
210                         std::string password,
211                         MapDrawControl &control
212                         );
213         
214         ~Client();
215         /*
216                 The name of the local player should already be set when
217                 calling this, as it is sent in the initialization.
218         */
219         void connect(Address address);
220         /*
221                 returns true when
222                         m_con.Connected() == true
223                         AND m_server_ser_ver != SER_FMT_VER_INVALID
224                 throws con::PeerNotFoundException if connection has been deleted,
225                 eg. timed out.
226         */
227         bool connectedAndInitialized();
228         /*
229                 Stuff that references the environment is valid only as
230                 long as this is not called. (eg. Players)
231                 If this throws a PeerNotFoundException, the connection has
232                 timed out.
233         */
234         void step(float dtime);
235
236         // Called from updater thread
237         // Returns dtime
238         //float asyncStep();
239
240         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
241         // Returns true if something was received
242         bool AsyncProcessPacket();
243         bool AsyncProcessData();
244         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
245
246         // Pops out a packet from the packet queue
247         //IncomingPacket getPacket();
248
249         void groundAction(u8 action, v3s16 nodepos_undersurface,
250                         v3s16 nodepos_oversurface, u16 item);
251         void clickObject(u8 button, v3s16 blockpos, s16 id, u16 item);
252         void clickActiveObject(u8 button, u16 id, u16 item);
253
254         void sendSignText(v3s16 blockpos, s16 id, std::string text);
255         void sendSignNodeText(v3s16 p, std::string text);
256         void sendInventoryAction(InventoryAction *a);
257         void sendChatMessage(const std::wstring &message);
258         void sendDamage(u8 damage);
259         
260         // locks envlock
261         void removeNode(v3s16 p);
262         // locks envlock
263         void addNode(v3s16 p, MapNode n);
264         
265         void updateCamera(v3f pos, v3f dir);
266         
267         // Returns InvalidPositionException if not found
268         MapNode getNode(v3s16 p);
269         // Wrapper to Map
270         NodeMetadata* getNodeMetadata(v3s16 p);
271
272         v3f getPlayerPosition();
273
274         void setPlayerControl(PlayerControl &control);
275         
276         // Returns true if the inventory of the local player has been
277         // updated from the server. If it is true, it is set to false.
278         bool getLocalInventoryUpdated();
279         // Copies the inventory of the local player to parameter
280         void getLocalInventory(Inventory &dst);
281         
282         InventoryContext *getInventoryContext();
283
284         Inventory* getInventory(InventoryContext *c, std::string id);
285         void inventoryAction(InventoryAction *a);
286
287         // Gets closest object pointed by the shootline
288         // Returns NULL if not found
289         MapBlockObject * getSelectedObject(
290                         f32 max_d,
291                         v3f from_pos_f_on_map,
292                         core::line3d<f32> shootline_on_map
293         );
294
295         // Gets closest object pointed by the shootline
296         // Returns NULL if not found
297         ClientActiveObject * getSelectedActiveObject(
298                         f32 max_d,
299                         v3f from_pos_f_on_map,
300                         core::line3d<f32> shootline_on_map
301         );
302
303         // Prints a line or two of info
304         void printDebugInfo(std::ostream &os);
305
306         u32 getDayNightRatio();
307
308         u16 getHP();
309
310         //void updateSomeExpiredMeshes();
311         
312         void setTempMod(v3s16 p, NodeMod mod)
313         {
314                 //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out
315                 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
316
317                 core::map<v3s16, MapBlock*> affected_blocks;
318                 ((ClientMap&)m_env.getMap()).setTempMod(p, mod,
319                                 &affected_blocks);
320
321                 for(core::map<v3s16, MapBlock*>::Iterator
322                                 i = affected_blocks.getIterator();
323                                 i.atEnd() == false; i++)
324                 {
325                         i.getNode()->getValue()->updateMesh(m_env.getDayNightRatio());
326                 }
327         }
328         void clearTempMod(v3s16 p)
329         {
330                 //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out
331                 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
332
333                 core::map<v3s16, MapBlock*> affected_blocks;
334                 ((ClientMap&)m_env.getMap()).clearTempMod(p,
335                                 &affected_blocks);
336
337                 for(core::map<v3s16, MapBlock*>::Iterator
338                                 i = affected_blocks.getIterator();
339                                 i.atEnd() == false; i++)
340                 {
341                         i.getNode()->getValue()->updateMesh(m_env.getDayNightRatio());
342                 }
343         }
344
345         float getAvgRtt()
346         {
347                 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
348                 con::Peer *peer = m_con.GetPeerNoEx(PEER_ID_SERVER);
349                 if(peer == NULL)
350                         return 0.0;
351                 return peer->avg_rtt;
352         }
353
354         bool getChatMessage(std::wstring &message)
355         {
356                 if(m_chat_queue.size() == 0)
357                         return false;
358                 message = m_chat_queue.pop_front();
359                 return true;
360         }
361
362         void addChatMessage(const std::wstring &message)
363         {
364                 //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out
365                 LocalPlayer *player = m_env.getLocalPlayer();
366                 assert(player != NULL);
367                 std::wstring name = narrow_to_wide(player->getName());
368                 m_chat_queue.push_back(
369                                 (std::wstring)L"<"+name+L"> "+message);
370         }
371
372         u64 getMapSeed(){ return m_map_seed; }
373
374         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false);
375         // Including blocks at appropriate edges
376         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false);
377
378         // Get event from queue. CE_NONE is returned if queue is empty.
379         ClientEvent getClientEvent();
380         
381         inline bool accessDenied()
382         {
383                 return m_access_denied;
384         }
385
386 private:
387         
388         // Virtual methods from con::PeerHandler
389         void peerAdded(con::Peer *peer);
390         void deletingPeer(con::Peer *peer, bool timeout);
391         
392         void ReceiveAll();
393         void Receive();
394         
395         void sendPlayerPos();
396         // This sends the player's current name etc to the server
397         void sendPlayerInfo();
398         
399         float m_packetcounter_timer;
400         float m_delete_unused_sectors_timer;
401         float m_connection_reinit_timer;
402         float m_avg_rtt_timer;
403         float m_playerpos_send_timer;
404         float m_ignore_damage_timer; // Used after server moves player
405
406         MeshUpdateThread m_mesh_update_thread;
407         
408         ClientEnvironment m_env;
409         
410         con::Connection m_con;
411
412         IrrlichtDevice *m_device;
413
414         v3f camera_position;
415         v3f camera_direction;
416         
417         // Server serialization version
418         u8 m_server_ser_ver;
419
420         // This is behind m_env_mutex.
421         bool m_inventory_updated;
422
423         core::map<v3s16, bool> m_active_blocks;
424
425         PacketCounter m_packetcounter;
426         
427         // Received from the server. 0-23999
428         u32 m_time_of_day;
429         
430         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
431         //s32 m_daynight_i;
432         //u32 m_daynight_ratio;
433
434         Queue<std::wstring> m_chat_queue;
435         
436         // The seed returned by the server in TOCLIENT_INIT is stored here
437         u64 m_map_seed;
438         
439         std::string m_password;
440         bool m_access_denied;
441
442         InventoryContext m_inventory_context;
443
444         Queue<ClientEvent> m_client_event_queue;
445 };
446
447 #endif // !SERVER
448
449 #endif // !CLIENT_HEADER
450