a3d43997c4ccc8bc49a111dfe249c12639a0b9ad
[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
31 class ClientNotReadyException : public BaseException
32 {
33 public:
34         ClientNotReadyException(const char *s):
35                 BaseException(s)
36         {}
37 };
38
39 class Client;
40
41 class ClientUpdateThread : public SimpleThread
42 {
43         Client *m_client;
44
45 public:
46
47         ClientUpdateThread(Client *client):
48                         SimpleThread(),
49                         m_client(client)
50         {
51         }
52
53         void * Thread();
54 };
55
56 struct IncomingPacket
57 {
58         IncomingPacket()
59         {
60                 m_data = NULL;
61                 m_datalen = 0;
62                 m_refcount = NULL;
63         }
64         IncomingPacket(const IncomingPacket &a)
65         {
66                 m_data = a.m_data;
67                 m_datalen = a.m_datalen;
68                 m_refcount = a.m_refcount;
69                 if(m_refcount != NULL)
70                         (*m_refcount)++;
71         }
72         IncomingPacket(u8 *data, u32 datalen)
73         {
74                 m_data = new u8[datalen];
75                 memcpy(m_data, data, datalen);
76                 m_datalen = datalen;
77                 m_refcount = new s32(1);
78         }
79         ~IncomingPacket()
80         {
81                 if(m_refcount != NULL){
82                         assert(*m_refcount > 0);
83                         (*m_refcount)--;
84                         if(*m_refcount == 0){
85                                 if(m_data != NULL)
86                                         delete[] m_data;
87                                 delete m_refcount;
88                         }
89                 }
90         }
91         /*IncomingPacket & operator=(IncomingPacket a)
92         {
93                 m_data = a.m_data;
94                 m_datalen = a.m_datalen;
95                 m_refcount = a.m_refcount;
96                 (*m_refcount)++;
97                 return *this;
98         }*/
99         u8 *m_data;
100         u32 m_datalen;
101         s32 *m_refcount;
102 };
103
104 // TODO: Remove this. It is not used as supposed.
105 class LazyMeshUpdater
106 {
107 public:
108         LazyMeshUpdater(Environment *env)
109         {
110                 m_env = env;
111         }
112         ~LazyMeshUpdater()
113         {
114                 /*
115                         TODO: This could be optimized. It will currently
116                         double-update some blocks.
117                 */
118                 for(core::map<v3s16, bool>::Iterator
119                                 i = m_blocks.getIterator();
120                                 i.atEnd() == false; i++)
121                 {
122                         v3s16 p = i.getNode()->getKey();
123                         m_env->updateMeshes(p);
124                 }
125                 m_blocks.clear();
126         }
127         void add(v3s16 p)
128         {
129                 m_blocks.insert(p, true);
130         }
131 private:
132         Environment *m_env;
133         core::map<v3s16, bool> m_blocks;
134 };
135
136 class Client : public con::PeerHandler
137 {
138 public:
139         /*
140                 NOTE: Every public method should be thread-safe
141         */
142         Client(
143                         IrrlichtDevice *device,
144                         const char *playername,
145                         JMutex &range_mutex,
146                         s16 &viewing_range_nodes,
147                         bool &viewing_range_all
148                         );
149         
150         ~Client();
151         /*
152                 The name of the local player should already be set when
153                 calling this, as it is sent in the initialization.
154         */
155         void connect(Address address);
156         /*
157                 returns true when
158                         m_con.Connected() == true
159                         AND m_server_ser_ver != SER_FMT_VER_INVALID
160                 throws con::PeerNotFoundException if connection has been deleted,
161                 eg. timed out.
162         */
163         bool connectedAndInitialized();
164         /*
165                 Stuff that references the environment is valid only as
166                 long as this is not called. (eg. Players)
167                 If this throws a PeerNotFoundException, the connection has
168                 timed out.
169         */
170         void step(float dtime);
171
172         // Called from updater thread
173         // Returns dtime
174         float asyncStep();
175
176         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
177         // Returns true if something was received
178         bool AsyncProcessPacket(LazyMeshUpdater &mesh_updater);
179         bool AsyncProcessData();
180         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
181
182         //TODO: Remove
183         bool isFetchingBlocks();
184
185         // Pops out a packet from the packet queue
186         IncomingPacket getPacket();
187
188         void groundAction(u8 action, v3s16 nodepos_undersurface,
189                         v3s16 nodepos_oversurface, u16 item);
190         void clickObject(u8 button, v3s16 blockpos, s16 id, u16 item);
191
192         void sendSignText(v3s16 blockpos, s16 id, std::string text);
193         
194         void updateCamera(v3f pos, v3f dir);
195         
196         // Returns InvalidPositionException if not found
197         MapNode getNode(v3s16 p);
198         // Returns InvalidPositionException if not found
199         //void setNode(v3s16 p, MapNode n);
200
201         // Returns InvalidPositionException if not found
202         //f32 getGroundHeight(v2s16 p);
203         // Returns InvalidPositionException if not found
204         //bool isNodeUnderground(v3s16 p);
205
206         // Note: The players should not be exposed outside
207         // Return value is valid until client is destroyed
208         //Player * getLocalPlayer();
209         // Return value is valid until step()
210         //core::list<Player*> getPlayers();
211         v3f getPlayerPosition();
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         // TODO: Functions for sending inventory editing commands to
221         //       server
222         
223         // Gets closest object pointed by the shootline
224         // Returns NULL if not found
225         MapBlockObject * getSelectedObject(
226                         f32 max_d,
227                         v3f from_pos_f_on_map,
228                         core::line3d<f32> shootline_on_map
229         );
230
231         // Prints a line or two of info
232         void printDebugInfo(std::ostream &os);
233
234         //s32 getDayNightIndex();
235         u32 getDayNightRatio();
236
237         //void updateSomeExpiredMeshes();
238         
239         void setTempMod(v3s16 p, NodeMod mod)
240         {
241                 JMutexAutoLock envlock(m_env_mutex);
242                 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
243                 v3s16 blockpos = ((ClientMap&)m_env.getMap()).setTempMod(p, mod);
244                 m_env.getMap().updateMeshes(blockpos, m_env.getDayNightRatio());
245         }
246         void clearTempMod(v3s16 p)
247         {
248                 JMutexAutoLock envlock(m_env_mutex);
249                 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
250                 v3s16 blockpos = ((ClientMap&)m_env.getMap()).clearTempMod(p);
251                 m_env.getMap().updateMeshes(blockpos, m_env.getDayNightRatio());
252         }
253         
254 private:
255         
256         // Virtual methods from con::PeerHandler
257         void peerAdded(con::Peer *peer);
258         void deletingPeer(con::Peer *peer, bool timeout);
259         
260         void ReceiveAll();
261         void Receive();
262         
263         void sendPlayerPos();
264         // This sends the player's current name etc to the server
265         void sendPlayerInfo();
266
267         float m_packetcounter_timer;
268         float m_delete_unused_sectors_timer;
269         float m_connection_reinit_timer;
270         float m_avg_rtt_timer;
271         float m_playerpos_send_timer;
272
273         ClientUpdateThread m_thread;
274         
275         // NOTE: If connection and environment are both to be locked,
276         // environment shall be locked first.
277
278         Environment m_env;
279         JMutex m_env_mutex;
280         
281         con::Connection m_con;
282         JMutex m_con_mutex;
283
284         /*core::map<v3s16, float> m_fetchblock_history;
285         JMutex m_fetchblock_mutex;*/
286
287         core::list<IncomingPacket> m_incoming_queue;
288         JMutex m_incoming_queue_mutex;
289
290         IrrlichtDevice *m_device;
291
292         v3f camera_position;
293         v3f camera_direction;
294         
295         // Server serialization version
296         u8 m_server_ser_ver;
297
298         float m_step_dtime;
299         JMutex m_step_dtime_mutex;
300
301         // This is behind m_env_mutex.
302         bool m_inventory_updated;
303
304         core::map<v3s16, bool> m_active_blocks;
305
306         PacketCounter m_packetcounter;
307         
308         // Received from the server. 0-23999
309         MutexedVariable<u32> m_time_of_day;
310         
311         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
312         //s32 m_daynight_i;
313         //u32 m_daynight_ratio;
314 };
315
316 #endif // !SERVER
317
318 #endif // !CLIENT_HEADER
319