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