]> git.lizzy.rs Git - minetest.git/blob - src/serverenvironment.h
Add callback on_mapblocks_changed
[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 #pragma once
21
22 #include "activeobject.h"
23 #include "environment.h"
24 #include "map.h"
25 #include "settings.h"
26 #include "server/activeobjectmgr.h"
27 #include "util/numeric.h"
28 #include "util/metricsbackend.h"
29 #include <set>
30 #include <random>
31
32 class IGameDef;
33 struct GameParams;
34 class RemotePlayer;
35 class PlayerDatabase;
36 class AuthDatabase;
37 class PlayerSAO;
38 class ServerEnvironment;
39 class ActiveBlockModifier;
40 struct StaticObject;
41 class ServerActiveObject;
42 class Server;
43 class ServerScripting;
44
45 /*
46         {Active, Loading} block modifier interface.
47
48         These are fed into ServerEnvironment at initialization time;
49         ServerEnvironment handles deleting them.
50 */
51
52 class ActiveBlockModifier
53 {
54 public:
55         ActiveBlockModifier() = default;
56         virtual ~ActiveBlockModifier() = default;
57
58         // Set of contents to trigger on
59         virtual const std::vector<std::string> &getTriggerContents() const = 0;
60         // Set of required neighbors (trigger doesn't happen if none are found)
61         // Empty = do not check neighbors
62         virtual const std::vector<std::string> &getRequiredNeighbors() const = 0;
63         // Trigger interval in seconds
64         virtual float getTriggerInterval() = 0;
65         // Random chance of (1 / return value), 0 is disallowed
66         virtual u32 getTriggerChance() = 0;
67         // Whether to modify chance to simulate time lost by an unnattended block
68         virtual bool getSimpleCatchUp() = 0;
69         // get min Y for apply abm
70         virtual s16 getMinY() = 0;
71         // get max Y for apply abm
72         virtual s16 getMaxY() = 0;
73         // This is called usually at interval for 1/chance of the nodes
74         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
75         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
76                 u32 active_object_count, u32 active_object_count_wider){};
77 };
78
79 struct ABMWithState
80 {
81         ActiveBlockModifier *abm;
82         float timer = 0.0f;
83
84         ABMWithState(ActiveBlockModifier *abm_);
85 };
86
87 struct LoadingBlockModifierDef
88 {
89         // Set of contents to trigger on
90         std::set<std::string> trigger_contents;
91         std::string name;
92         bool run_at_every_load = false;
93
94         virtual ~LoadingBlockModifierDef() = default;
95
96         virtual void trigger(ServerEnvironment *env, v3s16 p,
97                         MapNode n, float dtime_s) {};
98 };
99
100 struct LBMContentMapping
101 {
102         typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
103         lbm_map map;
104
105         std::vector<LoadingBlockModifierDef *> lbm_list;
106
107         // Needs to be separate method (not inside destructor),
108         // because the LBMContentMapping may be copied and destructed
109         // many times during operation in the lbm_lookup_map.
110         void deleteContents();
111         void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
112         const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
113 };
114
115 class LBMManager
116 {
117 public:
118         LBMManager() = default;
119         ~LBMManager();
120
121         // Don't call this after loadIntroductionTimes() ran.
122         void addLBMDef(LoadingBlockModifierDef *lbm_def);
123
124         void loadIntroductionTimes(const std::string &times,
125                 IGameDef *gamedef, u32 now);
126
127         // Don't call this before loadIntroductionTimes() ran.
128         std::string createIntroductionTimesString();
129
130         // Don't call this before loadIntroductionTimes() ran.
131         void applyLBMs(ServerEnvironment *env, MapBlock *block,
132                         u32 stamp, float dtime_s);
133
134         // Warning: do not make this std::unordered_map, order is relevant here
135         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
136
137 private:
138         // Once we set this to true, we can only query,
139         // not modify
140         bool m_query_mode = false;
141
142         // For m_query_mode == false:
143         // The key of the map is the LBM def's name.
144         // TODO make this std::unordered_map
145         std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
146
147         // For m_query_mode == true:
148         // The key of the map is the LBM def's first introduction time.
149         lbm_lookup_map m_lbm_lookup;
150
151         // Returns an iterator to the LBMs that were introduced
152         // after the given time. This is guaranteed to return
153         // valid values for everything
154         lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
155         { return m_lbm_lookup.lower_bound(time); }
156 };
157
158 /*
159         List of active blocks, used by ServerEnvironment
160 */
161
162 class ActiveBlockList
163 {
164 public:
165         void update(std::vector<PlayerSAO*> &active_players,
166                 s16 active_block_range,
167                 s16 active_object_range,
168                 std::set<v3s16> &blocks_removed,
169                 std::set<v3s16> &blocks_added);
170
171         bool contains(v3s16 p) const {
172                 return (m_list.find(p) != m_list.end());
173         }
174
175         auto size() const {
176                 return m_list.size();
177         }
178
179         void clear() {
180                 m_list.clear();
181         }
182
183         void remove(v3s16 p) {
184                 m_list.erase(p);
185                 m_abm_list.erase(p);
186         }
187
188         std::set<v3s16> m_list;
189         std::set<v3s16> m_abm_list;
190         // list of blocks that are always active, not modified by this class
191         std::set<v3s16> m_forceloaded_list;
192 };
193
194 /*
195         ServerEnvironment::m_on_mapblocks_changed_receiver
196 */
197 struct OnMapblocksChangedReceiver : public MapEventReceiver {
198         std::unordered_set<v3s16> modified_blocks;
199         bool receiving = false;
200
201         void onMapEditEvent(const MapEditEvent &event) override;
202 };
203
204 /*
205         Operation mode for ServerEnvironment::clearObjects()
206 */
207 enum ClearObjectsMode {
208         // Load and go through every mapblock, clearing objects
209                 CLEAR_OBJECTS_MODE_FULL,
210
211         // Clear objects immediately in loaded mapblocks;
212         // clear objects in unloaded mapblocks only when the mapblocks are next activated.
213                 CLEAR_OBJECTS_MODE_QUICK,
214 };
215
216 class ServerEnvironment final : public Environment
217 {
218 public:
219         ServerEnvironment(ServerMap *map, ServerScripting *script_iface,
220                 Server *server, const std::string &path_world, MetricsBackend *mb);
221         ~ServerEnvironment();
222
223         void init();
224
225         Map & getMap();
226
227         ServerMap & getServerMap();
228
229         //TODO find way to remove this fct!
230         ServerScripting* getScriptIface()
231         { return m_script; }
232
233         Server *getGameDef()
234         { return m_server; }
235
236         float getSendRecommendedInterval()
237         { return m_recommended_send_interval; }
238
239         void kickAllPlayers(AccessDeniedCode reason,
240                 const std::string &str_reason, bool reconnect);
241         // Save players
242         void saveLoadedPlayers(bool force = false);
243         void savePlayer(RemotePlayer *player);
244         PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
245                 bool is_singleplayer);
246         void addPlayer(RemotePlayer *player);
247         void removePlayer(RemotePlayer *player);
248         bool removePlayerFromDatabase(const std::string &name);
249
250         /*
251                 Save and load time of day and game timer
252         */
253         void saveMeta();
254         void loadMeta();
255
256         u32 addParticleSpawner(float exptime);
257         u32 addParticleSpawner(float exptime, u16 attached_id);
258         void deleteParticleSpawner(u32 id, bool remove_from_object = true);
259
260         /*
261                 External ActiveObject interface
262                 -------------------------------------------
263         */
264
265         ServerActiveObject* getActiveObject(u16 id)
266         {
267                 return m_ao_manager.getActiveObject(id);
268         }
269
270         /*
271                 Add an active object to the environment.
272                 Environment handles deletion of object.
273                 Object may be deleted by environment immediately.
274                 If id of object is 0, assigns a free id to it.
275                 Returns the id of the object.
276                 Returns 0 if not added and thus deleted.
277         */
278         u16 addActiveObject(ServerActiveObject *object);
279
280         /*
281                 Add an active object as a static object to the corresponding
282                 MapBlock.
283                 Caller allocates memory, ServerEnvironment frees memory.
284                 Return value: true if succeeded, false if failed.
285                 (note:  not used, pending removal from engine)
286         */
287         //bool addActiveObjectAsStatic(ServerActiveObject *object);
288
289         /*
290                 Find out what new objects have been added to
291                 inside a radius around a position
292         */
293         void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
294                 s16 player_radius,
295                 std::set<u16> &current_objects,
296                 std::queue<u16> &added_objects);
297
298         /*
299                 Find out what new objects have been removed from
300                 inside a radius around a position
301         */
302         void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
303                 s16 player_radius,
304                 std::set<u16> &current_objects,
305                 std::queue<u16> &removed_objects);
306
307         /*
308                 Get the next message emitted by some active object.
309                 Returns false if no messages are available, true otherwise.
310         */
311         bool getActiveObjectMessage(ActiveObjectMessage *dest);
312
313         virtual void getSelectedActiveObjects(
314                 const core::line3d<f32> &shootline_on_map,
315                 std::vector<PointedThing> &objects
316         );
317
318         /*
319                 Activate objects and dynamically modify for the dtime determined
320                 from timestamp and additional_dtime
321         */
322         void activateBlock(MapBlock *block, u32 additional_dtime=0);
323
324         /*
325                 {Active,Loading}BlockModifiers
326                 -------------------------------------------
327         */
328
329         void addActiveBlockModifier(ActiveBlockModifier *abm);
330         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
331
332         /*
333                 Other stuff
334                 -------------------------------------------
335         */
336
337         // Script-aware node setters
338         bool setNode(v3s16 p, const MapNode &n);
339         bool removeNode(v3s16 p);
340         bool swapNode(v3s16 p, const MapNode &n);
341
342         // Find the daylight value at pos with a Depth First Search
343         u8 findSunlight(v3s16 pos) const;
344
345         // Find all active objects inside a radius around a point
346         void getObjectsInsideRadius(std::vector<ServerActiveObject *> &objects, const v3f &pos, float radius,
347                         std::function<bool(ServerActiveObject *obj)> include_obj_cb)
348         {
349                 return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb);
350         }
351
352         // Find all active objects inside a box
353         void getObjectsInArea(std::vector<ServerActiveObject *> &objects, const aabb3f &box,
354                         std::function<bool(ServerActiveObject *obj)> include_obj_cb)
355         {
356                 return m_ao_manager.getObjectsInArea(box, objects, include_obj_cb);
357         }
358
359         // Clear objects, loading and going through every MapBlock
360         void clearObjects(ClearObjectsMode mode);
361
362         // This makes stuff happen
363         void step(f32 dtime);
364
365         u32 getGameTime() const { return m_game_time; }
366
367         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
368         float getMaxLagEstimate() { return m_max_lag_estimate; }
369
370         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; }
371
372         // Sorted by how ready a mapblock is
373         enum BlockStatus {
374                 BS_UNKNOWN,
375                 BS_EMERGING,
376                 BS_LOADED,
377                 BS_ACTIVE // always highest value
378         };
379         BlockStatus getBlockStatus(v3s16 blockpos);
380
381         // Sets the static object status all the active objects in the specified block
382         // This is only really needed for deleting blocks from the map
383         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
384                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
385
386         RemotePlayer *getPlayer(const session_t peer_id);
387         RemotePlayer *getPlayer(const char* name);
388         const std::vector<RemotePlayer *> getPlayers() const { return m_players; }
389         u32 getPlayerCount() const { return m_players.size(); }
390
391         static bool migratePlayersDatabase(const GameParams &game_params,
392                         const Settings &cmd_args);
393
394         AuthDatabase *getAuthDatabase() { return m_auth_database; }
395         static bool migrateAuthDatabase(const GameParams &game_params,
396                         const Settings &cmd_args);
397 private:
398
399         /**
400          * called if env_meta.txt doesn't exist (e.g. new world)
401          */
402         void loadDefaultMeta();
403
404         static PlayerDatabase *openPlayerDatabase(const std::string &name,
405                         const std::string &savedir, const Settings &conf);
406         static AuthDatabase *openAuthDatabase(const std::string &name,
407                         const std::string &savedir, const Settings &conf);
408         /*
409                 Internal ActiveObject interface
410                 -------------------------------------------
411         */
412
413         /*
414                 Add an active object to the environment.
415
416                 Called by addActiveObject.
417
418                 Object may be deleted by environment immediately.
419                 If id of object is 0, assigns a free id to it.
420                 Returns the id of the object.
421                 Returns 0 if not added and thus deleted.
422         */
423         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
424
425         /*
426                 Remove all objects that satisfy (isGone() && m_known_by_count==0)
427         */
428         void removeRemovedObjects();
429
430         /*
431                 Convert stored objects from block to active
432         */
433         void activateObjects(MapBlock *block, u32 dtime_s);
434
435         /*
436                 Convert objects that are not in active blocks to static.
437
438                 If m_known_by_count != 0, active object is not deleted, but static
439                 data is still updated.
440
441                 If force_delete is set, active object is deleted nevertheless. It
442                 shall only be set so in the destructor of the environment.
443         */
444         void deactivateFarObjects(bool force_delete);
445
446         /*
447                 A few helpers used by the three above methods
448         */
449         void deleteStaticFromBlock(
450                         ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
451         bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
452                         ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
453
454         /*
455                 Member variables
456         */
457
458         // The map
459         ServerMap *m_map;
460         // Lua state
461         ServerScripting* m_script;
462         // Server definition
463         Server *m_server;
464         // Active Object Manager
465         server::ActiveObjectMgr m_ao_manager;
466         // on_mapblocks_changed map event receiver
467         OnMapblocksChangedReceiver m_on_mapblocks_changed_receiver;
468         // World path
469         const std::string m_path_world;
470         // Outgoing network message buffer for active objects
471         std::queue<ActiveObjectMessage> m_active_object_messages;
472         // Some timers
473         float m_send_recommended_timer = 0.0f;
474         IntervalLimiter m_object_management_interval;
475         // List of active blocks
476         ActiveBlockList m_active_blocks;
477         int m_fast_active_block_divider = 1;
478         IntervalLimiter m_active_blocks_mgmt_interval;
479         IntervalLimiter m_active_block_modifier_interval;
480         IntervalLimiter m_active_blocks_nodemetadata_interval;
481         // Whether the variables below have been read from file yet
482         bool m_meta_loaded = false;
483         // Time from the beginning of the game in seconds.
484         // Incremented in step().
485         u32 m_game_time = 0;
486         // A helper variable for incrementing the latter
487         float m_game_time_fraction_counter = 0.0f;
488         // Time of last clearObjects call (game time).
489         // When a mapblock older than this is loaded, its objects are cleared.
490         u32 m_last_clear_objects_time = 0;
491         // Active block modifiers
492         std::vector<ABMWithState> m_abms;
493         LBMManager m_lbm_mgr;
494         // An interval for generally sending object positions and stuff
495         float m_recommended_send_interval = 0.1f;
496         // Estimate for general maximum lag as determined by server.
497         // Can raise to high values like 15s with eg. map generation mods.
498         float m_max_lag_estimate = 0.1f;
499
500         // peer_ids in here should be unique, except that there may be many 0s
501         std::vector<RemotePlayer*> m_players;
502
503         PlayerDatabase *m_player_database = nullptr;
504         AuthDatabase *m_auth_database = nullptr;
505
506         // Pseudo random generator for shuffling, etc.
507         std::mt19937 m_rgen;
508
509         // Particles
510         IntervalLimiter m_particle_management_interval;
511         std::unordered_map<u32, float> m_particle_spawners;
512         std::unordered_map<u32, u16> m_particle_spawner_attachments;
513
514         // Environment metrics
515         MetricCounterPtr m_step_time_counter;
516         MetricGaugePtr m_active_block_gauge;
517         MetricGaugePtr m_active_object_gauge;
518
519         ServerActiveObject* createSAO(ActiveObjectType type, v3f pos, const std::string &data);
520 };