LBM content mapping map doesn't need to be ordered, use std::unordered_map
[oweals/minetest.git] / src / serverenvironment.h
1 /*
2 Minetest
3 Copyright (C) 2010-2017 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 SERVER_ENVIRONMENT_HEADER
21 #define SERVER_ENVIRONMENT_HEADER
22
23 #include "environment.h"
24 #include "mapnode.h"
25 #include "mapblock.h"
26 #include <set>
27
28 class IGameDef;
29 class ServerMap;
30 struct GameParams;
31 class RemotePlayer;
32 class PlayerDatabase;
33 class PlayerSAO;
34 class ServerEnvironment;
35 class ActiveBlockModifier;
36 class ServerActiveObject;
37 class Server;
38 class ServerScripting;
39
40 /*
41         {Active, Loading} block modifier interface.
42
43         These are fed into ServerEnvironment at initialization time;
44         ServerEnvironment handles deleting them.
45 */
46
47 class ActiveBlockModifier
48 {
49 public:
50         ActiveBlockModifier(){};
51         virtual ~ActiveBlockModifier(){};
52
53         // Set of contents to trigger on
54         virtual const std::set<std::string> &getTriggerContents() const = 0;
55         // Set of required neighbors (trigger doesn't happen if none are found)
56         // Empty = do not check neighbors
57         virtual const std::set<std::string> &getRequiredNeighbors() const = 0;
58         // Trigger interval in seconds
59         virtual float getTriggerInterval() = 0;
60         // Random chance of (1 / return value), 0 is disallowed
61         virtual u32 getTriggerChance() = 0;
62         // Whether to modify chance to simulate time lost by an unnattended block
63         virtual bool getSimpleCatchUp() = 0;
64         // This is called usually at interval for 1/chance of the nodes
65         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
66         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
67                 u32 active_object_count, u32 active_object_count_wider){};
68 };
69
70 struct ABMWithState
71 {
72         ActiveBlockModifier *abm;
73         float timer = 0.0f;
74
75         ABMWithState(ActiveBlockModifier *abm_);
76 };
77
78 struct LoadingBlockModifierDef
79 {
80         // Set of contents to trigger on
81         std::set<std::string> trigger_contents;
82         std::string name;
83         bool run_at_every_load = false;
84
85         virtual ~LoadingBlockModifierDef() {}
86         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
87 };
88
89 struct LBMContentMapping
90 {
91         typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
92         lbm_map map;
93
94         std::vector<LoadingBlockModifierDef *> lbm_list;
95
96         // Needs to be separate method (not inside destructor),
97         // because the LBMContentMapping may be copied and destructed
98         // many times during operation in the lbm_lookup_map.
99         void deleteContents();
100         void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
101         const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
102 };
103
104 class LBMManager
105 {
106 public:
107         LBMManager() {}
108         ~LBMManager();
109
110         // Don't call this after loadIntroductionTimes() ran.
111         void addLBMDef(LoadingBlockModifierDef *lbm_def);
112
113         void loadIntroductionTimes(const std::string &times,
114                 IGameDef *gamedef, u32 now);
115
116         // Don't call this before loadIntroductionTimes() ran.
117         std::string createIntroductionTimesString();
118
119         // Don't call this before loadIntroductionTimes() ran.
120         void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
121
122         // Warning: do not make this std::unordered_map, order is relevant here
123         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
124
125 private:
126         // Once we set this to true, we can only query,
127         // not modify
128         bool m_query_mode = false;
129
130         // For m_query_mode == false:
131         // The key of the map is the LBM def's name.
132         // TODO make this std::unordered_map
133         std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
134
135         // For m_query_mode == true:
136         // The key of the map is the LBM def's first introduction time.
137         lbm_lookup_map m_lbm_lookup;
138
139         // Returns an iterator to the LBMs that were introduced
140         // after the given time. This is guaranteed to return
141         // valid values for everything
142         lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
143         { return m_lbm_lookup.lower_bound(time); }
144 };
145
146 /*
147         List of active blocks, used by ServerEnvironment
148 */
149
150 class ActiveBlockList
151 {
152 public:
153         void update(std::vector<v3s16> &active_positions,
154                 s16 radius,
155                 std::set<v3s16> &blocks_removed,
156                 std::set<v3s16> &blocks_added);
157
158         bool contains(v3s16 p){
159                 return (m_list.find(p) != m_list.end());
160         }
161
162         void clear(){
163                 m_list.clear();
164         }
165
166         std::set<v3s16> m_list;
167         std::set<v3s16> m_forceloaded_list;
168
169 private:
170 };
171
172 /*
173         Operation mode for ServerEnvironment::clearObjects()
174 */
175 enum ClearObjectsMode {
176         // Load and go through every mapblock, clearing objects
177                 CLEAR_OBJECTS_MODE_FULL,
178
179         // Clear objects immediately in loaded mapblocks;
180         // clear objects in unloaded mapblocks only when the mapblocks are next activated.
181                 CLEAR_OBJECTS_MODE_QUICK,
182 };
183
184 /*
185         The server-side environment.
186
187         This is not thread-safe. Server uses an environment mutex.
188 */
189
190 typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap;
191
192 class ServerEnvironment : public Environment
193 {
194 public:
195         ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
196                 Server *server, const std::string &path_world);
197         ~ServerEnvironment();
198
199         Map & getMap();
200
201         ServerMap & getServerMap();
202
203         //TODO find way to remove this fct!
204         ServerScripting* getScriptIface()
205         { return m_script; }
206
207         Server *getGameDef()
208         { return m_server; }
209
210         float getSendRecommendedInterval()
211         { return m_recommended_send_interval; }
212
213         void kickAllPlayers(AccessDeniedCode reason,
214                 const std::string &str_reason, bool reconnect);
215         // Save players
216         void saveLoadedPlayers();
217         void savePlayer(RemotePlayer *player);
218         PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, u16 peer_id,
219                 bool is_singleplayer);
220         void addPlayer(RemotePlayer *player);
221         void removePlayer(RemotePlayer *player);
222         bool removePlayerFromDatabase(const std::string &name);
223
224         /*
225                 Save and load time of day and game timer
226         */
227         void saveMeta();
228         void loadMeta();
229         // to be called instead of loadMeta if
230         // env_meta.txt doesn't exist (e.g. new world)
231         void loadDefaultMeta();
232
233         u32 addParticleSpawner(float exptime);
234         u32 addParticleSpawner(float exptime, u16 attached_id);
235         void deleteParticleSpawner(u32 id, bool remove_from_object = true);
236
237         /*
238                 External ActiveObject interface
239                 -------------------------------------------
240         */
241
242         ServerActiveObject* getActiveObject(u16 id);
243
244         /*
245                 Add an active object to the environment.
246                 Environment handles deletion of object.
247                 Object may be deleted by environment immediately.
248                 If id of object is 0, assigns a free id to it.
249                 Returns the id of the object.
250                 Returns 0 if not added and thus deleted.
251         */
252         u16 addActiveObject(ServerActiveObject *object);
253
254         /*
255                 Add an active object as a static object to the corresponding
256                 MapBlock.
257                 Caller allocates memory, ServerEnvironment frees memory.
258                 Return value: true if succeeded, false if failed.
259                 (note:  not used, pending removal from engine)
260         */
261         //bool addActiveObjectAsStatic(ServerActiveObject *object);
262
263         /*
264                 Find out what new objects have been added to
265                 inside a radius around a position
266         */
267         void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
268                 s16 player_radius,
269                 std::set<u16> &current_objects,
270                 std::queue<u16> &added_objects);
271
272         /*
273                 Find out what new objects have been removed from
274                 inside a radius around a position
275         */
276         void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
277                 s16 player_radius,
278                 std::set<u16> &current_objects,
279                 std::queue<u16> &removed_objects);
280
281         /*
282                 Get the next message emitted by some active object.
283                 Returns a message with id=0 if no messages are available.
284         */
285         ActiveObjectMessage getActiveObjectMessage();
286
287         virtual void getSelectedActiveObjects(
288                 const core::line3d<f32> &shootline_on_map,
289                 std::vector<PointedThing> &objects
290         );
291
292         /*
293                 Activate objects and dynamically modify for the dtime determined
294                 from timestamp and additional_dtime
295         */
296         void activateBlock(MapBlock *block, u32 additional_dtime=0);
297
298         /*
299                 {Active,Loading}BlockModifiers
300                 -------------------------------------------
301         */
302
303         void addActiveBlockModifier(ActiveBlockModifier *abm);
304         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
305
306         /*
307                 Other stuff
308                 -------------------------------------------
309         */
310
311         // Script-aware node setters
312         bool setNode(v3s16 p, const MapNode &n);
313         bool removeNode(v3s16 p);
314         bool swapNode(v3s16 p, const MapNode &n);
315
316         // Find all active objects inside a radius around a point
317         void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
318
319         // Clear objects, loading and going through every MapBlock
320         void clearObjects(ClearObjectsMode mode);
321
322         // This makes stuff happen
323         void step(f32 dtime);
324
325         //check if there's a line of sight between two positions
326         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
327
328         u32 getGameTime() const { return m_game_time; }
329
330         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
331         float getMaxLagEstimate() { return m_max_lag_estimate; }
332
333         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
334
335         // Sets the static object status all the active objects in the specified block
336         // This is only really needed for deleting blocks from the map
337         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
338                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
339
340         RemotePlayer *getPlayer(const u16 peer_id);
341         RemotePlayer *getPlayer(const char* name);
342
343         static bool migratePlayersDatabase(const GameParams &game_params,
344                         const Settings &cmd_args);
345 private:
346
347         static PlayerDatabase *openPlayerDatabase(const std::string &name,
348                         const std::string &savedir, const Settings &conf);
349         /*
350                 Internal ActiveObject interface
351                 -------------------------------------------
352         */
353
354         /*
355                 Add an active object to the environment.
356
357                 Called by addActiveObject.
358
359                 Object may be deleted by environment immediately.
360                 If id of object is 0, assigns a free id to it.
361                 Returns the id of the object.
362                 Returns 0 if not added and thus deleted.
363         */
364         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
365
366         /*
367                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
368         */
369         void removeRemovedObjects();
370
371         /*
372                 Convert stored objects from block to active
373         */
374         void activateObjects(MapBlock *block, u32 dtime_s);
375
376         /*
377                 Convert objects that are not in active blocks to static.
378
379                 If m_known_by_count != 0, active object is not deleted, but static
380                 data is still updated.
381
382                 If force_delete is set, active object is deleted nevertheless. It
383                 shall only be set so in the destructor of the environment.
384         */
385         void deactivateFarObjects(bool force_delete);
386
387         /*
388                 Member variables
389         */
390
391         // The map
392         ServerMap *m_map;
393         // Lua state
394         ServerScripting* m_script;
395         // Server definition
396         Server *m_server;
397         // World path
398         const std::string m_path_world;
399         // Active object list
400         ServerActiveObjectMap m_active_objects;
401         // Outgoing network message buffer for active objects
402         std::queue<ActiveObjectMessage> m_active_object_messages;
403         // Some timers
404         float m_send_recommended_timer = 0.0f;
405         IntervalLimiter m_object_management_interval;
406         // List of active blocks
407         ActiveBlockList m_active_blocks;
408         IntervalLimiter m_active_blocks_management_interval;
409         IntervalLimiter m_active_block_modifier_interval;
410         IntervalLimiter m_active_blocks_nodemetadata_interval;
411         int m_active_block_interval_overload_skip = 0;
412         // Time from the beginning of the game in seconds.
413         // Incremented in step().
414         u32 m_game_time = 0;
415         // A helper variable for incrementing the latter
416         float m_game_time_fraction_counter = 0.0f;
417         // Time of last clearObjects call (game time).
418         // When a mapblock older than this is loaded, its objects are cleared.
419         u32 m_last_clear_objects_time = 0;
420         // Active block modifiers
421         std::vector<ABMWithState> m_abms;
422         LBMManager m_lbm_mgr;
423         // An interval for generally sending object positions and stuff
424         float m_recommended_send_interval = 0.1f;
425         // Estimate for general maximum lag as determined by server.
426         // Can raise to high values like 15s with eg. map generation mods.
427         float m_max_lag_estimate = 0.1f;
428
429         // peer_ids in here should be unique, except that there may be many 0s
430         std::vector<RemotePlayer*> m_players;
431
432         PlayerDatabase *m_player_database = nullptr;
433
434         // Particles
435         IntervalLimiter m_particle_management_interval;
436         std::unordered_map<u32, float> m_particle_spawners;
437         std::unordered_map<u32, u16> m_particle_spawner_attachments;
438 };
439
440 #endif