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