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