84805b462074956c86d47cabbb1533f770e9a2ef
[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 "threading/atomic.h"
44 #include "network/networkprotocol.h" // for AccessDeniedCode
45
46 class ServerEnvironment;
47 class ActiveBlockModifier;
48 class ServerActiveObject;
49 class ITextureSource;
50 class IGameDef;
51 class Map;
52 class ServerMap;
53 class ClientMap;
54 class GameScripting;
55 class Player;
56 class RemotePlayer;
57 class PlayerSAO;
58 class PointedThing;
59
60 class Environment
61 {
62 public:
63         // Environment will delete the map passed to the constructor
64         Environment();
65         virtual ~Environment();
66
67         /*
68                 Step everything in environment.
69                 - Move players
70                 - Step mobs
71                 - Run timers of map
72         */
73         virtual void step(f32 dtime) = 0;
74
75         virtual Map & getMap() = 0;
76
77         u32 getDayNightRatio();
78
79         // 0-23999
80         virtual void setTimeOfDay(u32 time);
81         u32 getTimeOfDay();
82         float getTimeOfDayF();
83
84         void stepTimeOfDay(float dtime);
85
86         void setTimeOfDaySpeed(float speed);
87
88         void setDayNightRatioOverride(bool enable, u32 value);
89
90         u32 getDayCount();
91
92         // counter used internally when triggering ABMs
93         u32 m_added_objects;
94
95 protected:
96         GenericAtomic<float> m_time_of_day_speed;
97
98         /*
99          * Below: values managed by m_time_lock
100         */
101         // Time of day in milli-hours (0-23999); determines day and night
102         u32 m_time_of_day;
103         // Time of day in 0...1
104         float m_time_of_day_f;
105         // Stores the skew created by the float -> u32 conversion
106         // to be applied at next conversion, so that there is no real skew.
107         float m_time_conversion_skew;
108         // Overriding the day-night ratio is useful for custom sky visuals
109         bool m_enable_day_night_ratio_override;
110         u32 m_day_night_ratio_override;
111         // Days from the server start, accounts for time shift
112         // in game (e.g. /time or bed usage)
113         Atomic<u32> m_day_count;
114         /*
115          * Above: values managed by m_time_lock
116         */
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         float m_cache_active_block_mgmt_interval;
129         float m_cache_abm_interval;
130         float m_cache_nodetimer_interval;
131
132 private:
133         Mutex m_time_lock;
134
135         DISABLE_CLASS_COPY(Environment);
136 };
137
138 /*
139         {Active, Loading} block modifier interface.
140
141         These are fed into ServerEnvironment at initialization time;
142         ServerEnvironment handles deleting them.
143 */
144
145 class ActiveBlockModifier
146 {
147 public:
148         ActiveBlockModifier(){};
149         virtual ~ActiveBlockModifier(){};
150
151         // Set of contents to trigger on
152         virtual std::set<std::string> getTriggerContents()=0;
153         // Set of required neighbors (trigger doesn't happen if none are found)
154         // Empty = do not check neighbors
155         virtual std::set<std::string> getRequiredNeighbors()
156         { return std::set<std::string>(); }
157         // Trigger interval in seconds
158         virtual float getTriggerInterval() = 0;
159         // Random chance of (1 / return value), 0 is disallowed
160         virtual u32 getTriggerChance() = 0;
161         // Whether to modify chance to simulate time lost by an unnattended block
162         virtual bool getSimpleCatchUp() = 0;
163         // This is called usually at interval for 1/chance of the nodes
164         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
165         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
166                         u32 active_object_count, u32 active_object_count_wider){};
167 };
168
169 struct ABMWithState
170 {
171         ActiveBlockModifier *abm;
172         float timer;
173
174         ABMWithState(ActiveBlockModifier *abm_);
175 };
176
177 struct LoadingBlockModifierDef
178 {
179         // Set of contents to trigger on
180         std::set<std::string> trigger_contents;
181         std::string name;
182         bool run_at_every_load;
183
184         virtual ~LoadingBlockModifierDef() {}
185         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
186 };
187
188 struct LBMContentMapping
189 {
190         typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
191         container_map map;
192
193         std::vector<LoadingBlockModifierDef *> lbm_list;
194
195         // Needs to be separate method (not inside destructor),
196         // because the LBMContentMapping may be copied and destructed
197         // many times during operation in the lbm_lookup_map.
198         void deleteContents();
199         void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
200         const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
201 };
202
203 class LBMManager
204 {
205 public:
206         LBMManager():
207                 m_query_mode(false)
208         {}
209
210         ~LBMManager();
211
212         // Don't call this after loadIntroductionTimes() ran.
213         void addLBMDef(LoadingBlockModifierDef *lbm_def);
214
215         void loadIntroductionTimes(const std::string &times,
216                 IGameDef *gamedef, u32 now);
217
218         // Don't call this before loadIntroductionTimes() ran.
219         std::string createIntroductionTimesString();
220
221         // Don't call this before loadIntroductionTimes() ran.
222         void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
223
224         // Warning: do not make this std::unordered_map, order is relevant here
225         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
226
227 private:
228         // Once we set this to true, we can only query,
229         // not modify
230         bool m_query_mode;
231
232         // For m_query_mode == false:
233         // The key of the map is the LBM def's name.
234         // TODO make this std::unordered_map
235         std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
236
237         // For m_query_mode == true:
238         // The key of the map is the LBM def's first introduction time.
239         lbm_lookup_map m_lbm_lookup;
240
241         // Returns an iterator to the LBMs that were introduced
242         // after the given time. This is guaranteed to return
243         // valid values for everything
244         lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
245         { return m_lbm_lookup.lower_bound(time); }
246 };
247
248 /*
249         List of active blocks, used by ServerEnvironment
250 */
251
252 class ActiveBlockList
253 {
254 public:
255         void update(std::vector<v3s16> &active_positions,
256                         s16 radius,
257                         std::set<v3s16> &blocks_removed,
258                         std::set<v3s16> &blocks_added);
259
260         bool contains(v3s16 p){
261                 return (m_list.find(p) != m_list.end());
262         }
263
264         void clear(){
265                 m_list.clear();
266         }
267
268         std::set<v3s16> m_list;
269         std::set<v3s16> m_forceloaded_list;
270
271 private:
272 };
273
274 /*
275         Operation mode for ServerEnvironment::clearObjects()
276 */
277 enum ClearObjectsMode {
278         // Load and go through every mapblock, clearing objects
279         CLEAR_OBJECTS_MODE_FULL,
280
281         // Clear objects immediately in loaded mapblocks;
282         // clear objects in unloaded mapblocks only when the mapblocks are next activated.
283         CLEAR_OBJECTS_MODE_QUICK,
284 };
285
286 /*
287         The server-side environment.
288
289         This is not thread-safe. Server uses an environment mutex.
290 */
291
292 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
293
294 class ServerEnvironment : public Environment
295 {
296 public:
297         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
298                         IGameDef *gamedef, const std::string &path_world);
299         ~ServerEnvironment();
300
301         Map & getMap();
302
303         ServerMap & getServerMap();
304
305         //TODO find way to remove this fct!
306         GameScripting* getScriptIface()
307                 { return m_script; }
308
309         IGameDef *getGameDef()
310                 { return m_gamedef; }
311
312         float getSendRecommendedInterval()
313                 { return m_recommended_send_interval; }
314
315         void kickAllPlayers(AccessDeniedCode reason,
316                 const std::string &str_reason, bool reconnect);
317         // Save players
318         void saveLoadedPlayers();
319         void savePlayer(RemotePlayer *player);
320         RemotePlayer *loadPlayer(const std::string &playername, PlayerSAO *sao);
321         void addPlayer(RemotePlayer *player);
322         void removePlayer(RemotePlayer *player);
323
324         /*
325                 Save and load time of day and game timer
326         */
327         void saveMeta();
328         void loadMeta();
329         // to be called instead of loadMeta if
330         // env_meta.txt doesn't exist (e.g. new world)
331         void loadDefaultMeta();
332
333         u32 addParticleSpawner(float exptime);
334         u32 addParticleSpawner(float exptime, u16 attached_id);
335         void deleteParticleSpawner(u32 id, bool remove_from_object = true);
336
337         /*
338                 External ActiveObject interface
339                 -------------------------------------------
340         */
341
342         ServerActiveObject* getActiveObject(u16 id);
343
344         /*
345                 Add an active object to the environment.
346                 Environment handles deletion of object.
347                 Object may be deleted by environment immediately.
348                 If id of object is 0, assigns a free id to it.
349                 Returns the id of the object.
350                 Returns 0 if not added and thus deleted.
351         */
352         u16 addActiveObject(ServerActiveObject *object);
353
354         /*
355                 Add an active object as a static object to the corresponding
356                 MapBlock.
357                 Caller allocates memory, ServerEnvironment frees memory.
358                 Return value: true if succeeded, false if failed.
359                 (note:  not used, pending removal from engine)
360         */
361         //bool addActiveObjectAsStatic(ServerActiveObject *object);
362
363         /*
364                 Find out what new objects have been added to
365                 inside a radius around a position
366         */
367         void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
368                         s16 player_radius,
369                         std::set<u16> &current_objects,
370                         std::queue<u16> &added_objects);
371
372         /*
373                 Find out what new objects have been removed from
374                 inside a radius around a position
375         */
376         void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
377                         s16 player_radius,
378                         std::set<u16> &current_objects,
379                         std::queue<u16> &removed_objects);
380
381         /*
382                 Get the next message emitted by some active object.
383                 Returns a message with id=0 if no messages are available.
384         */
385         ActiveObjectMessage getActiveObjectMessage();
386
387         /*
388                 Activate objects and dynamically modify for the dtime determined
389                 from timestamp and additional_dtime
390         */
391         void activateBlock(MapBlock *block, u32 additional_dtime=0);
392
393         /*
394                 {Active,Loading}BlockModifiers
395                 -------------------------------------------
396         */
397
398         void addActiveBlockModifier(ActiveBlockModifier *abm);
399         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
400
401         /*
402                 Other stuff
403                 -------------------------------------------
404         */
405
406         // Script-aware node setters
407         bool setNode(v3s16 p, const MapNode &n);
408         bool removeNode(v3s16 p);
409         bool swapNode(v3s16 p, const MapNode &n);
410
411         // Find all active objects inside a radius around a point
412         void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
413
414         // Clear objects, loading and going through every MapBlock
415         void clearObjects(ClearObjectsMode mode);
416
417         // This makes stuff happen
418         void step(f32 dtime);
419
420         //check if there's a line of sight between two positions
421         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
422
423         u32 getGameTime() { return m_game_time; }
424
425         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
426         float getMaxLagEstimate() { return m_max_lag_estimate; }
427
428         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
429
430         // Sets the static object status all the active objects in the specified block
431         // This is only really needed for deleting blocks from the map
432         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
433                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
434
435         RemotePlayer *getPlayer(const u16 peer_id);
436         RemotePlayer *getPlayer(const char* name);
437 private:
438
439         /*
440                 Internal ActiveObject interface
441                 -------------------------------------------
442         */
443
444         /*
445                 Add an active object to the environment.
446
447                 Called by addActiveObject.
448
449                 Object may be deleted by environment immediately.
450                 If id of object is 0, assigns a free id to it.
451                 Returns the id of the object.
452                 Returns 0 if not added and thus deleted.
453         */
454         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
455
456         /*
457                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
458         */
459         void removeRemovedObjects();
460
461         /*
462                 Convert stored objects from block to active
463         */
464         void activateObjects(MapBlock *block, u32 dtime_s);
465
466         /*
467                 Convert objects that are not in active blocks to static.
468
469                 If m_known_by_count != 0, active object is not deleted, but static
470                 data is still updated.
471
472                 If force_delete is set, active object is deleted nevertheless. It
473                 shall only be set so in the destructor of the environment.
474         */
475         void deactivateFarObjects(bool force_delete);
476
477         /*
478                 Member variables
479         */
480
481         // The map
482         ServerMap *m_map;
483         // Lua state
484         GameScripting* m_script;
485         // Game definition
486         IGameDef *m_gamedef;
487         // World path
488         const std::string m_path_world;
489         // Active object list
490         ActiveObjectMap m_active_objects;
491         // Outgoing network message buffer for active objects
492         std::queue<ActiveObjectMessage> m_active_object_messages;
493         // Some timers
494         float m_send_recommended_timer;
495         IntervalLimiter m_object_management_interval;
496         // List of active blocks
497         ActiveBlockList m_active_blocks;
498         IntervalLimiter m_active_blocks_management_interval;
499         IntervalLimiter m_active_block_modifier_interval;
500         IntervalLimiter m_active_blocks_nodemetadata_interval;
501         int m_active_block_interval_overload_skip;
502         // Time from the beginning of the game in seconds.
503         // Incremented in step().
504         u32 m_game_time;
505         // A helper variable for incrementing the latter
506         float m_game_time_fraction_counter;
507         // Time of last clearObjects call (game time).
508         // When a mapblock older than this is loaded, its objects are cleared.
509         u32 m_last_clear_objects_time;
510         // Active block modifiers
511         std::vector<ABMWithState> m_abms;
512         LBMManager m_lbm_mgr;
513         // An interval for generally sending object positions and stuff
514         float m_recommended_send_interval;
515         // Estimate for general maximum lag as determined by server.
516         // Can raise to high values like 15s with eg. map generation mods.
517         float m_max_lag_estimate;
518
519         // peer_ids in here should be unique, except that there may be many 0s
520         std::vector<RemotePlayer*> m_players;
521
522         // Particles
523         IntervalLimiter m_particle_management_interval;
524         UNORDERED_MAP<u32, float> m_particle_spawners;
525         UNORDERED_MAP<u32, u16> m_particle_spawner_attachments;
526 };
527
528 #ifndef SERVER
529
530 #include "clientobject.h"
531 #include "content_cao.h"
532
533 class ClientSimpleObject;
534
535 /*
536         The client-side environment.
537
538         This is not thread-safe.
539         Must be called from main (irrlicht) thread (uses the SceneManager)
540         Client uses an environment mutex.
541 */
542
543 enum ClientEnvEventType
544 {
545         CEE_NONE,
546         CEE_PLAYER_DAMAGE,
547         CEE_PLAYER_BREATH
548 };
549
550 struct ClientEnvEvent
551 {
552         ClientEnvEventType type;
553         union {
554                 //struct{
555                 //} none;
556                 struct{
557                         u8 amount;
558                         bool send_to_server;
559                 } player_damage;
560                 struct{
561                         u16 amount;
562                 } player_breath;
563         };
564 };
565
566 class ClientEnvironment : public Environment
567 {
568 public:
569         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
570                         ITextureSource *texturesource, IGameDef *gamedef,
571                         IrrlichtDevice *device);
572         ~ClientEnvironment();
573
574         Map & getMap();
575         ClientMap & getClientMap();
576
577         IGameDef *getGameDef()
578         { return m_gamedef; }
579
580         void step(f32 dtime);
581
582         virtual void setLocalPlayer(LocalPlayer *player);
583         LocalPlayer *getLocalPlayer() { return m_local_player; }
584
585         /*
586                 ClientSimpleObjects
587         */
588
589         void addSimpleObject(ClientSimpleObject *simple);
590
591         /*
592                 ActiveObjects
593         */
594
595         GenericCAO* getGenericCAO(u16 id);
596         ClientActiveObject* getActiveObject(u16 id);
597
598         /*
599                 Adds an active object to the environment.
600                 Environment handles deletion of object.
601                 Object may be deleted by environment immediately.
602                 If id of object is 0, assigns a free id to it.
603                 Returns the id of the object.
604                 Returns 0 if not added and thus deleted.
605         */
606         u16 addActiveObject(ClientActiveObject *object);
607
608         void addActiveObject(u16 id, u8 type, const std::string &init_data);
609         void removeActiveObject(u16 id);
610
611         void processActiveObjectMessage(u16 id, const std::string &data);
612
613         /*
614                 Callbacks for activeobjects
615         */
616
617         void damageLocalPlayer(u8 damage, bool handle_hp=true);
618         void updateLocalPlayerBreath(u16 breath);
619
620         /*
621                 Client likes to call these
622         */
623
624         // Get all nearby objects
625         void getActiveObjects(v3f origin, f32 max_d,
626                         std::vector<DistanceSortedActiveObject> &dest);
627
628         // Get event from queue. CEE_NONE is returned if queue is empty.
629         ClientEnvEvent getClientEvent();
630
631         /*!
632          * Gets closest object pointed by the shootline.
633          * Returns NULL if not found.
634          *
635          * \param[in]  shootline_on_map    the shootline for
636          * the test in world coordinates
637          * \param[out] intersection_point  the first point where
638          * the shootline meets the object. Valid only if
639          * not NULL is returned.
640          * \param[out] intersection_normal the normal vector of
641          * the intersection, pointing outwards. Zero vector if
642          * the shootline starts in an active object.
643          * Valid only if not NULL is returned.
644          */
645         ClientActiveObject * getSelectedActiveObject(
646                 const core::line3d<f32> &shootline_on_map,
647                 v3f *intersection_point,
648                 v3s16 *intersection_normal
649         );
650
651         /*!
652          * Performs a raycast on the world.
653          * Returns the first thing the shootline meets.
654          *
655          * @param[in]  shootline         the shootline, starting from
656          * the camera position. This also gives the maximal distance
657          * of the search.
658          * @param[in]  liquids_pointable if false, liquids are ignored
659          * @param[in]  look_for_object   if false, objects are ignored
660          */
661         PointedThing getPointedThing(
662                 core::line3d<f32> shootline,
663                 bool liquids_pointable,
664                 bool look_for_object);
665
666         u16 attachement_parent_ids[USHRT_MAX + 1];
667
668         const std::list<std::string> &getPlayerNames() { return m_player_names; }
669         void addPlayerName(const std::string &name) { m_player_names.push_back(name); }
670         void removePlayerName(const std::string &name) { m_player_names.remove(name); }
671         void updateCameraOffset(v3s16 camera_offset)
672         { m_camera_offset = camera_offset; }
673         v3s16 getCameraOffset() const { return m_camera_offset; }
674 private:
675         ClientMap *m_map;
676         LocalPlayer *m_local_player;
677         scene::ISceneManager *m_smgr;
678         ITextureSource *m_texturesource;
679         IGameDef *m_gamedef;
680         IrrlichtDevice *m_irr;
681         UNORDERED_MAP<u16, ClientActiveObject*> m_active_objects;
682         std::vector<ClientSimpleObject*> m_simple_objects;
683         std::queue<ClientEnvEvent> m_client_event_queue;
684         IntervalLimiter m_active_object_light_update_interval;
685         IntervalLimiter m_lava_hurt_interval;
686         IntervalLimiter m_drowning_interval;
687         IntervalLimiter m_breathing_interval;
688         std::list<std::string> m_player_names;
689         v3s16 m_camera_offset;
690 };
691
692 #endif
693
694 #endif
695