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