Weather support
[oweals/minetest.git] / src / environment.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 ENVIRONMENT_HEADER
21 #define ENVIRONMENT_HEADER
22
23 /*
24         This class is the game's environment.
25         It contains:
26         - The map
27         - Players
28         - Other objects
29         - The current time in the game
30         - etc.
31 */
32
33 #include <set>
34 #include <list>
35 #include "irrlichttypes_extrabloated.h"
36 #include "player.h"
37 #include <ostream>
38 #include "activeobject.h"
39 #include "util/container.h"
40 #include "util/numeric.h"
41 #include "mapnode.h"
42 #include "mapblock.h"
43
44 class ServerEnvironment;
45 class ActiveBlockModifier;
46 class ServerActiveObject;
47 typedef struct lua_State lua_State;
48 class ITextureSource;
49 class IGameDef;
50 class Map;
51 class ServerMap;
52 class ClientMap;
53 class ScriptApi;
54
55 class Environment
56 {
57 public:
58         // Environment will delete the map passed to the constructor
59         Environment();
60         virtual ~Environment();
61
62         /*
63                 Step everything in environment.
64                 - Move players
65                 - Step mobs
66                 - Run timers of map
67         */
68         virtual void step(f32 dtime) = 0;
69
70         virtual Map & getMap() = 0;
71
72         virtual void addPlayer(Player *player);
73         void removePlayer(u16 peer_id);
74         Player * getPlayer(u16 peer_id);
75         Player * getPlayer(const char *name);
76         Player * getRandomConnectedPlayer();
77         Player * getNearestConnectedPlayer(v3f pos);
78         std::list<Player*> getPlayers();
79         std::list<Player*> getPlayers(bool ignore_disconnected);
80         void printPlayers(std::ostream &o);
81         
82         u32 getDayNightRatio();
83         
84         // 0-23999
85         virtual void setTimeOfDay(u32 time)
86         {
87                 m_time_of_day = time;
88                 m_time_of_day_f = (float)time / 24000.0;
89         }
90
91         u32 getTimeOfDay()
92         { return m_time_of_day; }
93
94         float getTimeOfDayF()
95         { return m_time_of_day_f; }
96
97         void stepTimeOfDay(float dtime);
98
99         void setTimeOfDaySpeed(float speed)
100         { m_time_of_day_speed = speed; }
101         
102         float getTimeOfDaySpeed()
103         { return m_time_of_day_speed; }
104
105 protected:
106         // peer_ids in here should be unique, except that there may be many 0s
107         std::list<Player*> m_players;
108         // Time of day in milli-hours (0-23999); determines day and night
109         u32 m_time_of_day;
110         // Time of day in 0...1
111         float m_time_of_day_f;
112         float m_time_of_day_speed;
113         // Used to buffer dtime for adding to m_time_of_day
114         float m_time_counter;
115 };
116
117 /*
118         Active block modifier interface.
119
120         These are fed into ServerEnvironment at initialization time;
121         ServerEnvironment handles deleting them.
122 */
123
124 class ActiveBlockModifier
125 {
126 public:
127         ActiveBlockModifier(){};
128         virtual ~ActiveBlockModifier(){};
129         
130         // Set of contents to trigger on
131         virtual std::set<std::string> getTriggerContents()=0;
132         // Set of required neighbors (trigger doesn't happen if none are found)
133         // Empty = do not check neighbors
134         virtual std::set<std::string> getRequiredNeighbors()
135         { return std::set<std::string>(); }
136         // Trigger interval in seconds
137         virtual float getTriggerInterval() = 0;
138         // Random chance of (1 / return value), 0 is disallowed
139         virtual u32 getTriggerChance() = 0;
140         // This is called usually at interval for 1/chance of the nodes
141         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
142         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
143                         u32 active_object_count, u32 active_object_count_wider){};
144 };
145
146 struct ABMWithState
147 {
148         ActiveBlockModifier *abm;
149         float timer;
150
151         ABMWithState(ActiveBlockModifier *abm_);
152 };
153
154 /*
155         List of active blocks, used by ServerEnvironment
156 */
157
158 class ActiveBlockList
159 {
160 public:
161         void update(std::list<v3s16> &active_positions,
162                         s16 radius,
163                         std::set<v3s16> &blocks_removed,
164                         std::set<v3s16> &blocks_added);
165
166         bool contains(v3s16 p){
167                 return (m_list.find(p) != m_list.end());
168         }
169
170         void clear(){
171                 m_list.clear();
172         }
173
174         std::set<v3s16> m_list;
175
176 private:
177 };
178
179 class IBackgroundBlockEmerger
180 {
181 public:
182         virtual void queueBlockEmerge(v3s16 blockpos, bool allow_generate)=0;
183 };
184
185 /*
186         The server-side environment.
187
188         This is not thread-safe. Server uses an environment mutex.
189 */
190
191 class ServerEnvironment : public Environment
192 {
193 public:
194         ServerEnvironment(ServerMap *map, ScriptApi *iface, IGameDef *gamedef,
195                         IBackgroundBlockEmerger *emerger);
196         ~ServerEnvironment();
197
198         Map & getMap();
199
200         ServerMap & getServerMap();
201
202         //TODO find way to remove this fct!
203         ScriptApi* getScriptIface()
204                 { return m_script; }
205
206         IGameDef *getGameDef()
207                 { return m_gamedef; }
208
209         float getSendRecommendedInterval()
210                 { return m_recommended_send_interval; }
211
212         /*
213                 Save players
214         */
215         void serializePlayers(const std::string &savedir);
216         void deSerializePlayers(const std::string &savedir);
217
218         /*
219                 Save and load time of day and game timer
220         */
221         void saveMeta(const std::string &savedir);
222         void loadMeta(const std::string &savedir);
223
224         /*
225                 External ActiveObject interface
226                 -------------------------------------------
227         */
228
229         ServerActiveObject* getActiveObject(u16 id);
230
231         /*
232                 Add an active object to the environment.
233                 Environment handles deletion of object.
234                 Object may be deleted by environment immediately.
235                 If id of object is 0, assigns a free id to it.
236                 Returns the id of the object.
237                 Returns 0 if not added and thus deleted.
238         */
239         u16 addActiveObject(ServerActiveObject *object);
240         
241         /*
242                 Add an active object as a static object to the corresponding
243                 MapBlock.
244                 Caller allocates memory, ServerEnvironment frees memory.
245                 Return value: true if succeeded, false if failed.
246                 (note:  not used, pending removal from engine)
247         */
248         //bool addActiveObjectAsStatic(ServerActiveObject *object);
249         
250         /*
251                 Find out what new objects have been added to
252                 inside a radius around a position
253         */
254         void getAddedActiveObjects(v3s16 pos, s16 radius,
255                         std::set<u16> &current_objects,
256                         std::set<u16> &added_objects);
257
258         /*
259                 Find out what new objects have been removed from
260                 inside a radius around a position
261         */
262         void getRemovedActiveObjects(v3s16 pos, s16 radius,
263                         std::set<u16> &current_objects,
264                         std::set<u16> &removed_objects);
265         
266         /*
267                 Get the next message emitted by some active object.
268                 Returns a message with id=0 if no messages are available.
269         */
270         ActiveObjectMessage getActiveObjectMessage();
271
272         /*
273                 Activate objects and dynamically modify for the dtime determined
274                 from timestamp and additional_dtime
275         */
276         void activateBlock(MapBlock *block, u32 additional_dtime=0);
277
278         /*
279                 ActiveBlockModifiers
280                 -------------------------------------------
281         */
282
283         void addActiveBlockModifier(ActiveBlockModifier *abm);
284
285         /*
286                 Other stuff
287                 -------------------------------------------
288         */
289
290         // Script-aware node setters
291         bool setNode(v3s16 p, const MapNode &n);
292         bool removeNode(v3s16 p);
293         
294         // Find all active objects inside a radius around a point
295         std::set<u16> getObjectsInsideRadius(v3f pos, float radius);
296         
297         // Clear all objects, loading and going through every MapBlock
298         void clearAllObjects();
299         
300         // This makes stuff happen
301         void step(f32 dtime);
302         
303         //check if there's a line of sight between two positions
304         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0);
305
306         u32 getGameTime() { return m_game_time; }
307 private:
308
309         /*
310                 Internal ActiveObject interface
311                 -------------------------------------------
312         */
313
314         /*
315                 Add an active object to the environment.
316
317                 Called by addActiveObject.
318
319                 Object may be deleted by environment immediately.
320                 If id of object is 0, assigns a free id to it.
321                 Returns the id of the object.
322                 Returns 0 if not added and thus deleted.
323         */
324         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
325         
326         /*
327                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
328         */
329         void removeRemovedObjects();
330         
331         /*
332                 Convert stored objects from block to active
333         */
334         void activateObjects(MapBlock *block, u32 dtime_s);
335         
336         /*
337                 Convert objects that are not in active blocks to static.
338
339                 If m_known_by_count != 0, active object is not deleted, but static
340                 data is still updated.
341
342                 If force_delete is set, active object is deleted nevertheless. It
343                 shall only be set so in the destructor of the environment.
344         */
345         void deactivateFarObjects(bool force_delete);
346
347         /*
348                 Member variables
349         */
350         
351         // The map
352         ServerMap *m_map;
353         // Lua state
354         ScriptApi* m_script;
355         // Game definition
356         IGameDef *m_gamedef;
357         // Background block emerger (the server, in practice)
358         IBackgroundBlockEmerger *m_emerger;
359         // Active object list
360         std::map<u16, ServerActiveObject*> m_active_objects;
361         // Outgoing network message buffer for active objects
362         Queue<ActiveObjectMessage> m_active_object_messages;
363         // Some timers
364         float m_random_spawn_timer; // used for experimental code
365         float m_send_recommended_timer;
366         IntervalLimiter m_object_management_interval;
367         // List of active blocks
368         ActiveBlockList m_active_blocks;
369         IntervalLimiter m_active_blocks_management_interval;
370         IntervalLimiter m_active_block_modifier_interval;
371         IntervalLimiter m_active_blocks_nodemetadata_interval;
372         int m_active_block_interval_overload_skip;
373         // Time from the beginning of the game in seconds.
374         // Incremented in step().
375         u32 m_game_time;
376         // A helper variable for incrementing the latter
377         float m_game_time_fraction_counter;
378         std::list<ABMWithState> m_abms;
379         // An interval for generally sending object positions and stuff
380         float m_recommended_send_interval;
381 };
382
383 #ifndef SERVER
384
385 #include "clientobject.h"
386 class ClientSimpleObject;
387
388 /*
389         The client-side environment.
390
391         This is not thread-safe.
392         Must be called from main (irrlicht) thread (uses the SceneManager)
393         Client uses an environment mutex.
394 */
395
396 enum ClientEnvEventType
397 {
398         CEE_NONE,
399         CEE_PLAYER_DAMAGE,
400         CEE_PLAYER_BREATH
401 };
402
403 struct ClientEnvEvent
404 {
405         ClientEnvEventType type;
406         union {
407                 struct{
408                 } none;
409                 struct{
410                         u8 amount;
411                         bool send_to_server;
412                 } player_damage;
413                 struct{
414                         u16 amount;
415                 } player_breath;
416         };
417 };
418
419 class ClientEnvironment : public Environment
420 {
421 public:
422         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
423                         ITextureSource *texturesource, IGameDef *gamedef,
424                         IrrlichtDevice *device);
425         ~ClientEnvironment();
426
427         Map & getMap();
428         ClientMap & getClientMap();
429
430         IGameDef *getGameDef()
431         { return m_gamedef; }
432
433         void step(f32 dtime);
434
435         virtual void addPlayer(Player *player);
436         LocalPlayer * getLocalPlayer();
437         
438         /*
439                 ClientSimpleObjects
440         */
441
442         void addSimpleObject(ClientSimpleObject *simple);
443
444         /*
445                 ActiveObjects
446         */
447         
448         ClientActiveObject* getActiveObject(u16 id);
449
450         /*
451                 Adds an active object to the environment.
452                 Environment handles deletion of object.
453                 Object may be deleted by environment immediately.
454                 If id of object is 0, assigns a free id to it.
455                 Returns the id of the object.
456                 Returns 0 if not added and thus deleted.
457         */
458         u16 addActiveObject(ClientActiveObject *object);
459
460         void addActiveObject(u16 id, u8 type, const std::string &init_data);
461         void removeActiveObject(u16 id);
462
463         void processActiveObjectMessage(u16 id, const std::string &data);
464
465         /*
466                 Callbacks for activeobjects
467         */
468
469         void damageLocalPlayer(u8 damage, bool handle_hp=true);
470         void updateLocalPlayerBreath(u16 breath);
471
472         /*
473                 Client likes to call these
474         */
475         
476         // Get all nearby objects
477         void getActiveObjects(v3f origin, f32 max_d,
478                         std::vector<DistanceSortedActiveObject> &dest);
479         
480         // Get event from queue. CEE_NONE is returned if queue is empty.
481         ClientEnvEvent getClientEvent();
482
483         std::vector<core::vector2d<int> > attachment_list; // X is child ID, Y is parent ID
484
485         std::list<std::string> getPlayerNames()
486         { return m_player_names; }
487         void addPlayerName(std::string name)
488         { m_player_names.push_back(name); }
489         void removePlayerName(std::string name)
490         { m_player_names.remove(name); }
491         
492 private:
493         ClientMap *m_map;
494         scene::ISceneManager *m_smgr;
495         ITextureSource *m_texturesource;
496         IGameDef *m_gamedef;
497         IrrlichtDevice *m_irr;
498         std::map<u16, ClientActiveObject*> m_active_objects;
499         std::list<ClientSimpleObject*> m_simple_objects;
500         Queue<ClientEnvEvent> m_client_event_queue;
501         IntervalLimiter m_active_object_light_update_interval;
502         IntervalLimiter m_lava_hurt_interval;
503         IntervalLimiter m_drowning_interval;
504         IntervalLimiter m_breathing_interval;
505         std::list<std::string> m_player_names;
506 };
507
508 #endif
509
510 #endif
511