Tune caves
[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 <set>
31 #include <vector>
32 #include "clientobject.h"
33 #include "utility.h" // For IntervalLimiter
34 #include "gamedef.h"
35 #include "inventorymanager.h"
36 #include "filesys.h"
37 #include "filecache.h"
38
39 struct MeshMakeData;
40 class MapBlockMesh;
41 class IGameDef;
42 class IWritableTextureSource;
43 class IWritableItemDefManager;
44 class IWritableNodeDefManager;
45 //class IWritableCraftDefManager;
46 class ClientEnvironment;
47 struct MapDrawControl;
48 class MtEventManager;
49
50 class ClientNotReadyException : public BaseException
51 {
52 public:
53         ClientNotReadyException(const char *s):
54                 BaseException(s)
55         {}
56 };
57
58 struct QueuedMeshUpdate
59 {
60         v3s16 p;
61         MeshMakeData *data;
62         bool ack_block_to_server;
63
64         QueuedMeshUpdate();
65         ~QueuedMeshUpdate();
66 };
67
68 /*
69         A thread-safe queue of mesh update tasks
70 */
71 class MeshUpdateQueue
72 {
73 public:
74         MeshUpdateQueue();
75
76         ~MeshUpdateQueue();
77         
78         /*
79                 peer_id=0 adds with nobody to send to
80         */
81         void addBlock(v3s16 p, MeshMakeData *data,
82                         bool ack_block_to_server, bool urgent);
83
84         // Returned pointer must be deleted
85         // Returns NULL if queue is empty
86         QueuedMeshUpdate * pop();
87
88         u32 size()
89         {
90                 JMutexAutoLock lock(m_mutex);
91                 return m_queue.size();
92         }
93         
94 private:
95         std::vector<QueuedMeshUpdate*> m_queue;
96         std::set<v3s16> m_urgents;
97         JMutex m_mutex;
98 };
99
100 struct MeshUpdateResult
101 {
102         v3s16 p;
103         MapBlockMesh *mesh;
104         bool ack_block_to_server;
105
106         MeshUpdateResult():
107                 p(-1338,-1338,-1338),
108                 mesh(NULL),
109                 ack_block_to_server(false)
110         {
111         }
112 };
113
114 class MeshUpdateThread : public SimpleThread
115 {
116 public:
117
118         MeshUpdateThread(IGameDef *gamedef):
119                 m_gamedef(gamedef)
120         {
121         }
122
123         void * Thread();
124
125         MeshUpdateQueue m_queue_in;
126
127         MutexedQueue<MeshUpdateResult> m_queue_out;
128
129         IGameDef *m_gamedef;
130 };
131
132 enum ClientEventType
133 {
134         CE_NONE,
135         CE_PLAYER_DAMAGE,
136         CE_PLAYER_FORCE_MOVE,
137         CE_DEATHSCREEN,
138         CE_TEXTURES_UPDATED
139 };
140
141 struct ClientEvent
142 {
143         ClientEventType type;
144         union{
145                 struct{
146                 } none;
147                 struct{
148                         u8 amount;
149                 } player_damage;
150                 struct{
151                         f32 pitch;
152                         f32 yaw;
153                 } player_force_move;
154                 struct{
155                         bool set_camera_point_target;
156                         f32 camera_point_target_x;
157                         f32 camera_point_target_y;
158                         f32 camera_point_target_z;
159                 } deathscreen;
160                 struct{
161                 } textures_updated;
162         };
163 };
164
165 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
166 {
167 public:
168         /*
169                 NOTE: Nothing is thread-safe here.
170         */
171
172         Client(
173                         IrrlichtDevice *device,
174                         const char *playername,
175                         std::string password,
176                         MapDrawControl &control,
177                         IWritableTextureSource *tsrc,
178                         IWritableItemDefManager *itemdef,
179                         IWritableNodeDefManager *nodedef,
180                         ISoundManager *sound,
181                         MtEventManager *event
182         );
183         
184         ~Client();
185         /*
186                 The name of the local player should already be set when
187                 calling this, as it is sent in the initialization.
188         */
189         void connect(Address address);
190         /*
191                 returns true when
192                         m_con.Connected() == true
193                         AND m_server_ser_ver != SER_FMT_VER_INVALID
194                 throws con::PeerNotFoundException if connection has been deleted,
195                 eg. timed out.
196         */
197         bool connectedAndInitialized();
198         /*
199                 Stuff that references the environment is valid only as
200                 long as this is not called. (eg. Players)
201                 If this throws a PeerNotFoundException, the connection has
202                 timed out.
203         */
204         void step(float dtime);
205
206         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
207         // Returns true if something was received
208         bool AsyncProcessPacket();
209         bool AsyncProcessData();
210         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
211
212         void interact(u8 action, const PointedThing& pointed);
213
214         void sendSignNodeText(v3s16 p, std::string text);
215         void sendInventoryAction(InventoryAction *a);
216         void sendChatMessage(const std::wstring &message);
217         void sendChangePassword(const std::wstring oldpassword,
218                 const std::wstring newpassword);
219         void sendDamage(u8 damage);
220         void sendRespawn();
221
222         ClientEnvironment& getEnv()
223         { return m_env; }
224         
225         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
226         void removeNode(v3s16 p);
227         void addNode(v3s16 p, MapNode n);
228         
229         void setPlayerControl(PlayerControl &control);
230
231         void selectPlayerItem(u16 item);
232         u16 getPlayerItem() const
233         { return m_playeritem; }
234
235         // Returns true if the inventory of the local player has been
236         // updated from the server. If it is true, it is set to false.
237         bool getLocalInventoryUpdated();
238         // Copies the inventory of the local player to parameter
239         void getLocalInventory(Inventory &dst);
240         
241         /* InventoryManager interface */
242         Inventory* getInventory(const InventoryLocation &loc);
243         void inventoryAction(InventoryAction *a);
244
245         // Gets closest object pointed by the shootline
246         // Returns NULL if not found
247         ClientActiveObject * getSelectedActiveObject(
248                         f32 max_d,
249                         v3f from_pos_f_on_map,
250                         core::line3d<f32> shootline_on_map
251         );
252
253         // Prints a line or two of info
254         void printDebugInfo(std::ostream &os);
255
256         core::list<std::wstring> getConnectedPlayerNames();
257
258         float getAnimationTime();
259
260         int getCrackLevel();
261         void setCrack(int level, v3s16 pos);
262
263         u16 getHP();
264
265         float getAvgRtt()
266         {
267                 try{
268                         return m_con.GetPeerAvgRTT(PEER_ID_SERVER);
269                 } catch(con::PeerNotFoundException){
270                         return 1337;
271                 }
272         }
273
274         bool getChatMessage(std::wstring &message);
275         void typeChatMessage(const std::wstring& message);
276
277         u64 getMapSeed(){ return m_map_seed; }
278
279         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
280         // Including blocks at appropriate edges
281         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
282         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
283
284         // Get event from queue. CE_NONE is returned if queue is empty.
285         ClientEvent getClientEvent();
286         
287         bool accessDenied()
288         { return m_access_denied; }
289
290         std::wstring accessDeniedReason()
291         { return m_access_denied_reason; }
292
293         float mediaReceiveProgress()
294         { return m_media_receive_progress; }
295
296         bool texturesReceived()
297         { return m_media_received; }
298         bool itemdefReceived()
299         { return m_itemdef_received; }
300         bool nodedefReceived()
301         { return m_nodedef_received; }
302         
303         void afterContentReceived();
304
305         float getRTT(void);
306
307         // IGameDef interface
308         virtual IItemDefManager* getItemDefManager();
309         virtual INodeDefManager* getNodeDefManager();
310         virtual ICraftDefManager* getCraftDefManager();
311         virtual ITextureSource* getTextureSource();
312         virtual u16 allocateUnknownNodeId(const std::string &name);
313         virtual ISoundManager* getSoundManager();
314         virtual MtEventManager* getEventManager();
315
316 private:
317         
318         // Insert a media file appropriately into the appropriate manager
319         bool loadMedia(const std::string &data, const std::string &filename);
320         
321         // Virtual methods from con::PeerHandler
322         void peerAdded(con::Peer *peer);
323         void deletingPeer(con::Peer *peer, bool timeout);
324         
325         void ReceiveAll();
326         void Receive();
327         
328         void sendPlayerPos();
329         // This sends the player's current name etc to the server
330         void sendPlayerInfo();
331         // Send the item number 'item' as player item to the server
332         void sendPlayerItem(u16 item);
333         
334         float m_packetcounter_timer;
335         float m_connection_reinit_timer;
336         float m_avg_rtt_timer;
337         float m_playerpos_send_timer;
338         float m_ignore_damage_timer; // Used after server moves player
339         IntervalLimiter m_map_timer_and_unload_interval;
340
341         IWritableTextureSource *m_tsrc;
342         IWritableItemDefManager *m_itemdef;
343         IWritableNodeDefManager *m_nodedef;
344         ISoundManager *m_sound;
345         MtEventManager *m_event;
346
347         MeshUpdateThread m_mesh_update_thread;
348         ClientEnvironment m_env;
349         con::Connection m_con;
350         IrrlichtDevice *m_device;
351         // Server serialization version
352         u8 m_server_ser_ver;
353         u16 m_playeritem;
354         bool m_inventory_updated;
355         Inventory *m_inventory_from_server;
356         float m_inventory_from_server_age;
357         core::map<v3s16, bool> m_active_blocks;
358         PacketCounter m_packetcounter;
359         // Block mesh animation parameters
360         float m_animation_time;
361         int m_crack_level;
362         v3s16 m_crack_pos;
363         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
364         //s32 m_daynight_i;
365         //u32 m_daynight_ratio;
366         Queue<std::wstring> m_chat_queue;
367         // The seed returned by the server in TOCLIENT_INIT is stored here
368         u64 m_map_seed;
369         std::string m_password;
370         bool m_access_denied;
371         std::wstring m_access_denied_reason;
372         Queue<ClientEvent> m_client_event_queue;
373         FileCache m_media_cache;
374         // Mapping from media file name to SHA1 checksum
375         core::map<std::string, std::string> m_media_name_sha1_map;
376         float m_media_receive_progress;
377         bool m_media_received;
378         bool m_itemdef_received;
379         bool m_nodedef_received;
380         friend class FarMesh;
381
382         // time_of_day speed approximation for old protocol
383         bool m_time_of_day_set;
384         float m_last_time_of_day_f;
385         float m_time_of_day_update_timer;
386
387         // Sounds
388         float m_removed_sounds_check_timer;
389         // Mapping from server sound ids to our sound ids
390         std::map<s32, int> m_sounds_server_to_client;
391         // And the other way!
392         std::map<int, s32> m_sounds_client_to_server;
393         // And relations to objects
394         std::map<int, u16> m_sounds_to_objects;
395 };
396
397 #endif // !SERVER
398
399 #endif // !CLIENT_HEADER
400