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