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