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