]> git.lizzy.rs Git - minetest.git/blob - src/environment.h
b59ce83c16dd31d17177b9e97eae79cb72af48f4
[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
308         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
309         float getMaxLagEstimate() { return m_max_lag_estimate; }
310 private:
311
312         /*
313                 Internal ActiveObject interface
314                 -------------------------------------------
315         */
316
317         /*
318                 Add an active object to the environment.
319
320                 Called by addActiveObject.
321
322                 Object may be deleted by environment immediately.
323                 If id of object is 0, assigns a free id to it.
324                 Returns the id of the object.
325                 Returns 0 if not added and thus deleted.
326         */
327         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
328         
329         /*
330                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
331         */
332         void removeRemovedObjects();
333         
334         /*
335                 Convert stored objects from block to active
336         */
337         void activateObjects(MapBlock *block, u32 dtime_s);
338         
339         /*
340                 Convert objects that are not in active blocks to static.
341
342                 If m_known_by_count != 0, active object is not deleted, but static
343                 data is still updated.
344
345                 If force_delete is set, active object is deleted nevertheless. It
346                 shall only be set so in the destructor of the environment.
347         */
348         void deactivateFarObjects(bool force_delete);
349
350         /*
351                 Member variables
352         */
353         
354         // The map
355         ServerMap *m_map;
356         // Lua state
357         ScriptApi* m_script;
358         // Game definition
359         IGameDef *m_gamedef;
360         // Background block emerger (the server, in practice)
361         IBackgroundBlockEmerger *m_emerger;
362         // Active object list
363         std::map<u16, ServerActiveObject*> m_active_objects;
364         // Outgoing network message buffer for active objects
365         Queue<ActiveObjectMessage> m_active_object_messages;
366         // Some timers
367         float m_random_spawn_timer; // used for experimental code
368         float m_send_recommended_timer;
369         IntervalLimiter m_object_management_interval;
370         // List of active blocks
371         ActiveBlockList m_active_blocks;
372         IntervalLimiter m_active_blocks_management_interval;
373         IntervalLimiter m_active_block_modifier_interval;
374         IntervalLimiter m_active_blocks_nodemetadata_interval;
375         int m_active_block_interval_overload_skip;
376         // Time from the beginning of the game in seconds.
377         // Incremented in step().
378         u32 m_game_time;
379         // A helper variable for incrementing the latter
380         float m_game_time_fraction_counter;
381         std::list<ABMWithState> m_abms;
382         // An interval for generally sending object positions and stuff
383         float m_recommended_send_interval;
384         // Estimate for general maximum lag as determined by server.
385         // Can raise to high values like 15s with eg. map generation mods.
386         float m_max_lag_estimate;
387 };
388
389 #ifndef SERVER
390
391 #include "clientobject.h"
392 class ClientSimpleObject;
393
394 /*
395         The client-side environment.
396
397         This is not thread-safe.
398         Must be called from main (irrlicht) thread (uses the SceneManager)
399         Client uses an environment mutex.
400 */
401
402 enum ClientEnvEventType
403 {
404         CEE_NONE,
405         CEE_PLAYER_DAMAGE,
406         CEE_PLAYER_BREATH
407 };
408
409 struct ClientEnvEvent
410 {
411         ClientEnvEventType type;
412         union {
413                 struct{
414                 } none;
415                 struct{
416                         u8 amount;
417                         bool send_to_server;
418                 } player_damage;
419                 struct{
420                         u16 amount;
421                 } player_breath;
422         };
423 };
424
425 class ClientEnvironment : public Environment
426 {
427 public:
428         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
429                         ITextureSource *texturesource, IGameDef *gamedef,
430                         IrrlichtDevice *device);
431         ~ClientEnvironment();
432
433         Map & getMap();
434         ClientMap & getClientMap();
435
436         IGameDef *getGameDef()
437         { return m_gamedef; }
438
439         void step(f32 dtime);
440
441         virtual void addPlayer(Player *player);
442         LocalPlayer * getLocalPlayer();
443         
444         /*
445                 ClientSimpleObjects
446         */
447
448         void addSimpleObject(ClientSimpleObject *simple);
449
450         /*
451                 ActiveObjects
452         */
453         
454         ClientActiveObject* getActiveObject(u16 id);
455
456         /*
457                 Adds an active object to the environment.
458                 Environment handles deletion of object.
459                 Object may be deleted by environment immediately.
460                 If id of object is 0, assigns a free id to it.
461                 Returns the id of the object.
462                 Returns 0 if not added and thus deleted.
463         */
464         u16 addActiveObject(ClientActiveObject *object);
465
466         void addActiveObject(u16 id, u8 type, const std::string &init_data);
467         void removeActiveObject(u16 id);
468
469         void processActiveObjectMessage(u16 id, const std::string &data);
470
471         /*
472                 Callbacks for activeobjects
473         */
474
475         void damageLocalPlayer(u8 damage, bool handle_hp=true);
476         void updateLocalPlayerBreath(u16 breath);
477
478         /*
479                 Client likes to call these
480         */
481         
482         // Get all nearby objects
483         void getActiveObjects(v3f origin, f32 max_d,
484                         std::vector<DistanceSortedActiveObject> &dest);
485         
486         // Get event from queue. CEE_NONE is returned if queue is empty.
487         ClientEnvEvent getClientEvent();
488
489         std::vector<core::vector2d<int> > attachment_list; // X is child ID, Y is parent ID
490
491         std::list<std::string> getPlayerNames()
492         { return m_player_names; }
493         void addPlayerName(std::string name)
494         { m_player_names.push_back(name); }
495         void removePlayerName(std::string name)
496         { m_player_names.remove(name); }
497         
498 private:
499         ClientMap *m_map;
500         scene::ISceneManager *m_smgr;
501         ITextureSource *m_texturesource;
502         IGameDef *m_gamedef;
503         IrrlichtDevice *m_irr;
504         std::map<u16, ClientActiveObject*> m_active_objects;
505         std::list<ClientSimpleObject*> m_simple_objects;
506         Queue<ClientEnvEvent> m_client_event_queue;
507         IntervalLimiter m_active_object_light_update_interval;
508         IntervalLimiter m_lava_hurt_interval;
509         IntervalLimiter m_drowning_interval;
510         IntervalLimiter m_breathing_interval;
511         std::list<std::string> m_player_names;
512 };
513
514 #endif
515
516 #endif
517