utility.h: Change Buffer's interface to be more compatible with SharedBuffer's interf...
[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         CE_DEATHSCREEN,
118 };
119
120 struct ClientEvent
121 {
122         ClientEventType type;
123         union{
124                 struct{
125                 } none;
126                 struct{
127                         u8 amount;
128                 } player_damage;
129                 struct{
130                         f32 pitch;
131                         f32 yaw;
132                 } player_force_move;
133                 struct{
134                         bool set_camera_point_target;
135                         f32 camera_point_target_x;
136                         f32 camera_point_target_y;
137                         f32 camera_point_target_z;
138                 } deathscreen;
139         };
140 };
141
142 class Client : public con::PeerHandler, public InventoryManager
143 {
144 public:
145         /*
146                 NOTE: Nothing is thread-safe here.
147         */
148
149         Client(
150                         IrrlichtDevice *device,
151                         const char *playername,
152                         std::string password,
153                         MapDrawControl &control
154                         );
155         
156         ~Client();
157         /*
158                 The name of the local player should already be set when
159                 calling this, as it is sent in the initialization.
160         */
161         void connect(Address address);
162         /*
163                 returns true when
164                         m_con.Connected() == true
165                         AND m_server_ser_ver != SER_FMT_VER_INVALID
166                 throws con::PeerNotFoundException if connection has been deleted,
167                 eg. timed out.
168         */
169         bool connectedAndInitialized();
170         /*
171                 Stuff that references the environment is valid only as
172                 long as this is not called. (eg. Players)
173                 If this throws a PeerNotFoundException, the connection has
174                 timed out.
175         */
176         void step(float dtime);
177
178         // Called from updater thread
179         // Returns dtime
180         //float asyncStep();
181
182         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
183         // Returns true if something was received
184         bool AsyncProcessPacket();
185         bool AsyncProcessData();
186         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
187
188         // Pops out a packet from the packet queue
189         //IncomingPacket getPacket();
190
191         void groundAction(u8 action, v3s16 nodepos_undersurface,
192                         v3s16 nodepos_oversurface, u16 item);
193         void clickActiveObject(u8 button, u16 id, u16 item_i);
194
195         void sendSignNodeText(v3s16 p, std::string text);
196         void sendInventoryAction(InventoryAction *a);
197         void sendChatMessage(const std::wstring &message);
198         void sendChangePassword(const std::wstring oldpassword,
199                 const std::wstring newpassword);
200         void sendDamage(u8 damage);
201         void sendRespawn();
202         
203         // locks envlock
204         void removeNode(v3s16 p);
205         // locks envlock
206         void addNode(v3s16 p, MapNode n);
207         
208         void updateCamera(v3f pos, v3f dir, f32 fov);
209         
210         void renderPostFx();
211         
212         // Returns InvalidPositionException if not found
213         MapNode getNode(v3s16 p);
214         // Wrapper to Map
215         NodeMetadata* getNodeMetadata(v3s16 p);
216
217         LocalPlayer* getLocalPlayer();
218
219         void setPlayerControl(PlayerControl &control);
220
221         void selectPlayerItem(u16 item);
222
223         // Returns true if the inventory of the local player has been
224         // updated from the server. If it is true, it is set to false.
225         bool getLocalInventoryUpdated();
226         // Copies the inventory of the local player to parameter
227         void getLocalInventory(Inventory &dst);
228         
229         InventoryContext *getInventoryContext();
230
231         Inventory* getInventory(InventoryContext *c, std::string id);
232         void inventoryAction(InventoryAction *a);
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                 try{
255                         return m_con.GetPeerAvgRTT(PEER_ID_SERVER);
256                 } catch(con::PeerNotFoundException){
257                         return 1337;
258                 }
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                 if (message[0] == L'/') {
272                         m_chat_queue.push_back(
273                                 (std::wstring)L"issued command: "+message);
274                         return;
275                 }
276
277                 //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out
278                 LocalPlayer *player = m_env.getLocalPlayer();
279                 assert(player != NULL);
280                 std::wstring name = narrow_to_wide(player->getName());
281                 m_chat_queue.push_back(
282                                 (std::wstring)L"<"+name+L"> "+message);
283         }
284
285         u64 getMapSeed(){ return m_map_seed; }
286
287         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false);
288         // Including blocks at appropriate edges
289         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false);
290
291         // Get event from queue. CE_NONE is returned if queue is empty.
292         ClientEvent getClientEvent();
293         
294         inline bool accessDenied()
295         {
296                 return m_access_denied;
297         }
298
299         inline std::wstring accessDeniedReason()
300         {
301                 return m_access_denied_reason;
302         }
303
304         float getRTT(void);
305
306 private:
307         
308         // Virtual methods from con::PeerHandler
309         void peerAdded(con::Peer *peer);
310         void deletingPeer(con::Peer *peer, bool timeout);
311         
312         void ReceiveAll();
313         void Receive();
314         
315         void sendPlayerPos();
316         // This sends the player's current name etc to the server
317         void sendPlayerInfo();
318         // Send the item number 'item' as player item to the server
319         void sendPlayerItem(u16 item);
320         
321         float m_packetcounter_timer;
322         float m_connection_reinit_timer;
323         float m_avg_rtt_timer;
324         float m_playerpos_send_timer;
325         float m_ignore_damage_timer; // Used after server moves player
326         IntervalLimiter m_map_timer_and_unload_interval;
327
328         MeshUpdateThread m_mesh_update_thread;
329         
330         ClientEnvironment m_env;
331         
332         con::Connection m_con;
333
334         IrrlichtDevice *m_device;
335
336         // Server serialization version
337         u8 m_server_ser_ver;
338
339         // This is behind m_env_mutex.
340         bool m_inventory_updated;
341
342         core::map<v3s16, bool> m_active_blocks;
343
344         PacketCounter m_packetcounter;
345         
346         // Received from the server. 0-23999
347         u32 m_time_of_day;
348         
349         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
350         //s32 m_daynight_i;
351         //u32 m_daynight_ratio;
352
353         Queue<std::wstring> m_chat_queue;
354         
355         // The seed returned by the server in TOCLIENT_INIT is stored here
356         u64 m_map_seed;
357         
358         std::string m_password;
359         bool m_access_denied;
360         std::wstring m_access_denied_reason;
361
362         InventoryContext m_inventory_context;
363
364         Queue<ClientEvent> m_client_event_queue;
365
366         friend class FarMesh;
367 };
368
369 #endif // !SERVER
370
371 #endif // !CLIENT_HEADER
372