]> git.lizzy.rs Git - minetest.git/blob - src/serverenvironment.h
Add on_flood() callback.
[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 class RemotePlayer;
31 class PlayerSAO;
32 class ServerEnvironment;
33 class ActiveBlockModifier;
34 class ServerActiveObject;
35 class Server;
36 class ServerScripting;
37
38 /*
39         {Active, Loading} block modifier interface.
40
41         These are fed into ServerEnvironment at initialization time;
42         ServerEnvironment handles deleting them.
43 */
44
45 class ActiveBlockModifier
46 {
47 public:
48         ActiveBlockModifier(){};
49         virtual ~ActiveBlockModifier(){};
50
51         // Set of contents to trigger on
52         virtual std::set<std::string> getTriggerContents()=0;
53         // Set of required neighbors (trigger doesn't happen if none are found)
54         // Empty = do not check neighbors
55         virtual std::set<std::string> getRequiredNeighbors()
56         { return std::set<std::string>(); }
57         // Trigger interval in seconds
58         virtual float getTriggerInterval() = 0;
59         // Random chance of (1 / return value), 0 is disallowed
60         virtual u32 getTriggerChance() = 0;
61         // Whether to modify chance to simulate time lost by an unnattended block
62         virtual bool getSimpleCatchUp() = 0;
63         // This is called usually at interval for 1/chance of the nodes
64         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
65         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
66                 u32 active_object_count, u32 active_object_count_wider){};
67 };
68
69 struct ABMWithState
70 {
71         ActiveBlockModifier *abm;
72         float timer;
73
74         ABMWithState(ActiveBlockModifier *abm_);
75 };
76
77 struct LoadingBlockModifierDef
78 {
79         // Set of contents to trigger on
80         std::set<std::string> trigger_contents;
81         std::string name;
82         bool run_at_every_load;
83
84         virtual ~LoadingBlockModifierDef() {}
85         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
86 };
87
88 struct LBMContentMapping
89 {
90         typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
91         container_map map;
92
93         std::vector<LoadingBlockModifierDef *> lbm_list;
94
95         // Needs to be separate method (not inside destructor),
96         // because the LBMContentMapping may be copied and destructed
97         // many times during operation in the lbm_lookup_map.
98         void deleteContents();
99         void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
100         const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
101 };
102
103 class LBMManager
104 {
105 public:
106         LBMManager():
107                 m_query_mode(false)
108         {}
109
110         ~LBMManager();
111
112         // Don't call this after loadIntroductionTimes() ran.
113         void addLBMDef(LoadingBlockModifierDef *lbm_def);
114
115         void loadIntroductionTimes(const std::string &times,
116                 IGameDef *gamedef, u32 now);
117
118         // Don't call this before loadIntroductionTimes() ran.
119         std::string createIntroductionTimesString();
120
121         // Don't call this before loadIntroductionTimes() ran.
122         void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
123
124         // Warning: do not make this std::unordered_map, order is relevant here
125         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
126
127 private:
128         // Once we set this to true, we can only query,
129         // not modify
130         bool m_query_mode;
131
132         // For m_query_mode == false:
133         // The key of the map is the LBM def's name.
134         // TODO make this std::unordered_map
135         std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
136
137         // For m_query_mode == true:
138         // The key of the map is the LBM def's first introduction time.
139         lbm_lookup_map m_lbm_lookup;
140
141         // Returns an iterator to the LBMs that were introduced
142         // after the given time. This is guaranteed to return
143         // valid values for everything
144         lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
145         { return m_lbm_lookup.lower_bound(time); }
146 };
147
148 /*
149         List of active blocks, used by ServerEnvironment
150 */
151
152 class ActiveBlockList
153 {
154 public:
155         void update(std::vector<v3s16> &active_positions,
156                 s16 radius,
157                 std::set<v3s16> &blocks_removed,
158                 std::set<v3s16> &blocks_added);
159
160         bool contains(v3s16 p){
161                 return (m_list.find(p) != m_list.end());
162         }
163
164         void clear(){
165                 m_list.clear();
166         }
167
168         std::set<v3s16> m_list;
169         std::set<v3s16> m_forceloaded_list;
170
171 private:
172 };
173
174 /*
175         Operation mode for ServerEnvironment::clearObjects()
176 */
177 enum ClearObjectsMode {
178         // Load and go through every mapblock, clearing objects
179                 CLEAR_OBJECTS_MODE_FULL,
180
181         // Clear objects immediately in loaded mapblocks;
182         // clear objects in unloaded mapblocks only when the mapblocks are next activated.
183                 CLEAR_OBJECTS_MODE_QUICK,
184 };
185
186 /*
187         The server-side environment.
188
189         This is not thread-safe. Server uses an environment mutex.
190 */
191
192 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
193
194 class ServerEnvironment : public Environment
195 {
196 public:
197         ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
198                 Server *server, const std::string &path_world);
199         ~ServerEnvironment();
200
201         Map & getMap();
202
203         ServerMap & getServerMap();
204
205         //TODO find way to remove this fct!
206         ServerScripting* getScriptIface()
207         { return m_script; }
208
209         Server *getGameDef()
210         { return m_server; }
211
212         float getSendRecommendedInterval()
213         { return m_recommended_send_interval; }
214
215         void kickAllPlayers(AccessDeniedCode reason,
216                 const std::string &str_reason, bool reconnect);
217         // Save players
218         void saveLoadedPlayers();
219         void savePlayer(RemotePlayer *player);
220         RemotePlayer *loadPlayer(const std::string &playername, PlayerSAO *sao);
221         void addPlayer(RemotePlayer *player);
222         void removePlayer(RemotePlayer *player);
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         /*
288                 Activate objects and dynamically modify for the dtime determined
289                 from timestamp and additional_dtime
290         */
291         void activateBlock(MapBlock *block, u32 additional_dtime=0);
292
293         /*
294                 {Active,Loading}BlockModifiers
295                 -------------------------------------------
296         */
297
298         void addActiveBlockModifier(ActiveBlockModifier *abm);
299         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
300
301         /*
302                 Other stuff
303                 -------------------------------------------
304         */
305
306         // Script-aware node setters
307         bool setNode(v3s16 p, const MapNode &n);
308         bool removeNode(v3s16 p);
309         bool swapNode(v3s16 p, const MapNode &n);
310
311         // Find all active objects inside a radius around a point
312         void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
313
314         // Clear objects, loading and going through every MapBlock
315         void clearObjects(ClearObjectsMode mode);
316
317         // This makes stuff happen
318         void step(f32 dtime);
319
320         //check if there's a line of sight between two positions
321         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
322
323         u32 getGameTime() const { return m_game_time; }
324
325         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
326         float getMaxLagEstimate() { return m_max_lag_estimate; }
327
328         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
329
330         // Sets the static object status all the active objects in the specified block
331         // This is only really needed for deleting blocks from the map
332         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
333                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
334
335         RemotePlayer *getPlayer(const u16 peer_id);
336         RemotePlayer *getPlayer(const char* name);
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         ServerScripting* m_script;
385         // Server definition
386         Server *m_server;
387         // World path
388         const std::string m_path_world;
389         // Active object list
390         ActiveObjectMap 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         // Time of last clearObjects call (game time).
408         // When a mapblock older than this is loaded, its objects are cleared.
409         u32 m_last_clear_objects_time;
410         // Active block modifiers
411         std::vector<ABMWithState> m_abms;
412         LBMManager m_lbm_mgr;
413         // An interval for generally sending object positions and stuff
414         float m_recommended_send_interval;
415         // Estimate for general maximum lag as determined by server.
416         // Can raise to high values like 15s with eg. map generation mods.
417         float m_max_lag_estimate;
418
419         // peer_ids in here should be unique, except that there may be many 0s
420         std::vector<RemotePlayer*> m_players;
421
422         // Particles
423         IntervalLimiter m_particle_management_interval;
424         UNORDERED_MAP<u32, float> m_particle_spawners;
425         UNORDERED_MAP<u32, u16> m_particle_spawner_attachments;
426 };
427
428 #endif