Performance improvement: Use std::list instead of std::vector for request_media,...
[oweals/minetest.git] / src / environment.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 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 ENVIRONMENT_HEADER
21 #define ENVIRONMENT_HEADER
22
23 /*
24         This class is the game's environment.
25         It contains:
26         - The map
27         - Players
28         - Other objects
29         - The current time in the game
30         - etc.
31 */
32
33 #include <set>
34 #include <list>
35 #include <map>
36 #include "irr_v3d.h"
37 #include "activeobject.h"
38 #include "util/numeric.h"
39 #include "mapnode.h"
40 #include "mapblock.h"
41 #include "jthread/jmutex.h"
42
43 class ServerEnvironment;
44 class ActiveBlockModifier;
45 class ServerActiveObject;
46 class ITextureSource;
47 class IGameDef;
48 class Map;
49 class ServerMap;
50 class ClientMap;
51 class GameScripting;
52 class Player;
53
54 class Environment
55 {
56 public:
57         // Environment will delete the map passed to the constructor
58         Environment();
59         virtual ~Environment();
60
61         /*
62                 Step everything in environment.
63                 - Move players
64                 - Step mobs
65                 - Run timers of map
66         */
67         virtual void step(f32 dtime) = 0;
68
69         virtual Map & getMap() = 0;
70
71         virtual void addPlayer(Player *player);
72         void removePlayer(u16 peer_id);
73         void removePlayer(const char *name);
74         Player * getPlayer(u16 peer_id);
75         Player * getPlayer(const char *name);
76         Player * getRandomConnectedPlayer();
77         Player * getNearestConnectedPlayer(v3f pos);
78         std::vector<Player*> getPlayers();
79         std::vector<Player*> getPlayers(bool ignore_disconnected);
80
81         u32 getDayNightRatio();
82
83         // 0-23999
84         virtual void setTimeOfDay(u32 time);
85         u32 getTimeOfDay();
86         float getTimeOfDayF();
87
88         void stepTimeOfDay(float dtime);
89
90         void setTimeOfDaySpeed(float speed);
91         float getTimeOfDaySpeed();
92
93         void setDayNightRatioOverride(bool enable, u32 value)
94         {
95                 m_enable_day_night_ratio_override = enable;
96                 m_day_night_ratio_override = value;
97         }
98
99         // counter used internally when triggering ABMs
100         u32 m_added_objects;
101
102 protected:
103         // peer_ids in here should be unique, except that there may be many 0s
104         std::vector<Player*> m_players;
105         // Time of day in milli-hours (0-23999); determines day and night
106         u32 m_time_of_day;
107         // Time of day in 0...1
108         float m_time_of_day_f;
109         float m_time_of_day_speed;
110         // Used to buffer dtime for adding to m_time_of_day
111         float m_time_counter;
112         // Overriding the day-night ratio is useful for custom sky visuals
113         bool m_enable_day_night_ratio_override;
114         u32 m_day_night_ratio_override;
115
116         /* TODO: Add a callback function so these can be updated when a setting
117          *       changes.  At this point in time it doesn't matter (e.g. /set
118          *       is documented to change server settings only)
119          *
120          * TODO: Local caching of settings is not optimal and should at some stage
121          *       be updated to use a global settings object for getting thse values
122          *       (as opposed to the this local caching). This can be addressed in
123          *       a later release.
124          */
125         bool m_cache_enable_shaders;
126
127 private:
128         JMutex m_timeofday_lock;
129         JMutex m_time_lock;
130
131 };
132
133 /*
134         Active block modifier interface.
135
136         These are fed into ServerEnvironment at initialization time;
137         ServerEnvironment handles deleting them.
138 */
139
140 class ActiveBlockModifier
141 {
142 public:
143         ActiveBlockModifier(){};
144         virtual ~ActiveBlockModifier(){};
145
146         // Set of contents to trigger on
147         virtual std::set<std::string> getTriggerContents()=0;
148         // Set of required neighbors (trigger doesn't happen if none are found)
149         // Empty = do not check neighbors
150         virtual std::set<std::string> getRequiredNeighbors()
151         { return std::set<std::string>(); }
152         // Trigger interval in seconds
153         virtual float getTriggerInterval() = 0;
154         // Random chance of (1 / return value), 0 is disallowed
155         virtual u32 getTriggerChance() = 0;
156         // This is called usually at interval for 1/chance of the nodes
157         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
158         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
159                         u32 active_object_count, u32 active_object_count_wider){};
160 };
161
162 struct ABMWithState
163 {
164         ActiveBlockModifier *abm;
165         float timer;
166
167         ABMWithState(ActiveBlockModifier *abm_);
168 };
169
170 /*
171         List of active blocks, used by ServerEnvironment
172 */
173
174 class ActiveBlockList
175 {
176 public:
177         void update(std::vector<v3s16> &active_positions,
178                         s16 radius,
179                         std::set<v3s16> &blocks_removed,
180                         std::set<v3s16> &blocks_added);
181
182         bool contains(v3s16 p){
183                 return (m_list.find(p) != m_list.end());
184         }
185
186         void clear(){
187                 m_list.clear();
188         }
189
190         std::set<v3s16> m_list;
191         std::set<v3s16> m_forceloaded_list;
192
193 private:
194 };
195
196 /*
197         The server-side environment.
198
199         This is not thread-safe. Server uses an environment mutex.
200 */
201
202 class ServerEnvironment : public Environment
203 {
204 public:
205         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
206                         IGameDef *gamedef, const std::string &path_world);
207         ~ServerEnvironment();
208
209         Map & getMap();
210
211         ServerMap & getServerMap();
212
213         //TODO find way to remove this fct!
214         GameScripting* getScriptIface()
215                 { return m_script; }
216
217         IGameDef *getGameDef()
218                 { return m_gamedef; }
219
220         float getSendRecommendedInterval()
221                 { return m_recommended_send_interval; }
222
223         // Save players
224         void saveLoadedPlayers();
225         void savePlayer(const std::string &playername);
226         Player *loadPlayer(const std::string &playername);
227
228         /*
229                 Save and load time of day and game timer
230         */
231         void saveMeta();
232         void loadMeta();
233
234         /*
235                 External ActiveObject interface
236                 -------------------------------------------
237         */
238
239         ServerActiveObject* getActiveObject(u16 id);
240
241         /*
242                 Add an active object to the environment.
243                 Environment handles deletion of object.
244                 Object may be deleted by environment immediately.
245                 If id of object is 0, assigns a free id to it.
246                 Returns the id of the object.
247                 Returns 0 if not added and thus deleted.
248         */
249         u16 addActiveObject(ServerActiveObject *object);
250
251         /*
252                 Add an active object as a static object to the corresponding
253                 MapBlock.
254                 Caller allocates memory, ServerEnvironment frees memory.
255                 Return value: true if succeeded, false if failed.
256                 (note:  not used, pending removal from engine)
257         */
258         //bool addActiveObjectAsStatic(ServerActiveObject *object);
259
260         /*
261                 Find out what new objects have been added to
262                 inside a radius around a position
263         */
264         void getAddedActiveObjects(v3s16 pos, s16 radius,
265                         s16 player_radius,
266                         std::set<u16> &current_objects,
267                         std::set<u16> &added_objects);
268
269         /*
270                 Find out what new objects have been removed from
271                 inside a radius around a position
272         */
273         void getRemovedActiveObjects(v3s16 pos, s16 radius,
274                         s16 player_radius,
275                         std::set<u16> &current_objects,
276                         std::set<u16> &removed_objects);
277
278         /*
279                 Get the next message emitted by some active object.
280                 Returns a message with id=0 if no messages are available.
281         */
282         ActiveObjectMessage getActiveObjectMessage();
283
284         /*
285                 Activate objects and dynamically modify for the dtime determined
286                 from timestamp and additional_dtime
287         */
288         void activateBlock(MapBlock *block, u32 additional_dtime=0);
289
290         /*
291                 ActiveBlockModifiers
292                 -------------------------------------------
293         */
294
295         void addActiveBlockModifier(ActiveBlockModifier *abm);
296
297         /*
298                 Other stuff
299                 -------------------------------------------
300         */
301
302         // Script-aware node setters
303         bool setNode(v3s16 p, const MapNode &n);
304         bool removeNode(v3s16 p);
305         bool swapNode(v3s16 p, const MapNode &n);
306
307         // Find all active objects inside a radius around a point
308         std::set<u16> getObjectsInsideRadius(v3f pos, float radius);
309
310         // Clear all objects, loading and going through every MapBlock
311         void clearAllObjects();
312
313         // This makes stuff happen
314         void step(f32 dtime);
315
316         //check if there's a line of sight between two positions
317         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
318
319         u32 getGameTime() { return m_game_time; }
320
321         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
322         float getMaxLagEstimate() { return m_max_lag_estimate; }
323
324         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
325
326 private:
327
328         /*
329                 Internal ActiveObject interface
330                 -------------------------------------------
331         */
332
333         /*
334                 Add an active object to the environment.
335
336                 Called by addActiveObject.
337
338                 Object may be deleted by environment immediately.
339                 If id of object is 0, assigns a free id to it.
340                 Returns the id of the object.
341                 Returns 0 if not added and thus deleted.
342         */
343         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
344
345         /*
346                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
347         */
348         void removeRemovedObjects();
349
350         /*
351                 Convert stored objects from block to active
352         */
353         void activateObjects(MapBlock *block, u32 dtime_s);
354
355         /*
356                 Convert objects that are not in active blocks to static.
357
358                 If m_known_by_count != 0, active object is not deleted, but static
359                 data is still updated.
360
361                 If force_delete is set, active object is deleted nevertheless. It
362                 shall only be set so in the destructor of the environment.
363         */
364         void deactivateFarObjects(bool force_delete);
365
366         /*
367                 Member variables
368         */
369
370         // The map
371         ServerMap *m_map;
372         // Lua state
373         GameScripting* m_script;
374         // Game definition
375         IGameDef *m_gamedef;
376         // World path
377         const std::string m_path_world;
378         // Active object list
379         std::map<u16, ServerActiveObject*> m_active_objects;
380         // Outgoing network message buffer for active objects
381         std::list<ActiveObjectMessage> m_active_object_messages;
382         // Some timers
383         float m_send_recommended_timer;
384         IntervalLimiter m_object_management_interval;
385         // List of active blocks
386         ActiveBlockList m_active_blocks;
387         IntervalLimiter m_active_blocks_management_interval;
388         IntervalLimiter m_active_block_modifier_interval;
389         IntervalLimiter m_active_blocks_nodemetadata_interval;
390         int m_active_block_interval_overload_skip;
391         // Time from the beginning of the game in seconds.
392         // Incremented in step().
393         u32 m_game_time;
394         // A helper variable for incrementing the latter
395         float m_game_time_fraction_counter;
396         std::vector<ABMWithState> m_abms;
397         // An interval for generally sending object positions and stuff
398         float m_recommended_send_interval;
399         // Estimate for general maximum lag as determined by server.
400         // Can raise to high values like 15s with eg. map generation mods.
401         float m_max_lag_estimate;
402 };
403
404 #ifndef SERVER
405
406 #include "clientobject.h"
407 class ClientSimpleObject;
408
409 /*
410         The client-side environment.
411
412         This is not thread-safe.
413         Must be called from main (irrlicht) thread (uses the SceneManager)
414         Client uses an environment mutex.
415 */
416
417 enum ClientEnvEventType
418 {
419         CEE_NONE,
420         CEE_PLAYER_DAMAGE,
421         CEE_PLAYER_BREATH
422 };
423
424 struct ClientEnvEvent
425 {
426         ClientEnvEventType type;
427         union {
428                 //struct{
429                 //} none;
430                 struct{
431                         u8 amount;
432                         bool send_to_server;
433                 } player_damage;
434                 struct{
435                         u16 amount;
436                 } player_breath;
437         };
438 };
439
440 class ClientEnvironment : public Environment
441 {
442 public:
443         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
444                         ITextureSource *texturesource, IGameDef *gamedef,
445                         IrrlichtDevice *device);
446         ~ClientEnvironment();
447
448         Map & getMap();
449         ClientMap & getClientMap();
450
451         IGameDef *getGameDef()
452         { return m_gamedef; }
453
454         void step(f32 dtime);
455
456         virtual void addPlayer(Player *player);
457         LocalPlayer * getLocalPlayer();
458
459         /*
460                 ClientSimpleObjects
461         */
462
463         void addSimpleObject(ClientSimpleObject *simple);
464
465         /*
466                 ActiveObjects
467         */
468
469         ClientActiveObject* getActiveObject(u16 id);
470
471         /*
472                 Adds an active object to the environment.
473                 Environment handles deletion of object.
474                 Object may be deleted by environment immediately.
475                 If id of object is 0, assigns a free id to it.
476                 Returns the id of the object.
477                 Returns 0 if not added and thus deleted.
478         */
479         u16 addActiveObject(ClientActiveObject *object);
480
481         void addActiveObject(u16 id, u8 type, const std::string &init_data);
482         void removeActiveObject(u16 id);
483
484         void processActiveObjectMessage(u16 id, const std::string &data);
485
486         /*
487                 Callbacks for activeobjects
488         */
489
490         void damageLocalPlayer(u8 damage, bool handle_hp=true);
491         void updateLocalPlayerBreath(u16 breath);
492
493         /*
494                 Client likes to call these
495         */
496
497         // Get all nearby objects
498         void getActiveObjects(v3f origin, f32 max_d,
499                         std::vector<DistanceSortedActiveObject> &dest);
500
501         // Get event from queue. CEE_NONE is returned if queue is empty.
502         ClientEnvEvent getClientEvent();
503
504         u16 m_attachements[USHRT_MAX];
505
506         std::list<std::string> getPlayerNames()
507         { return m_player_names; }
508         void addPlayerName(std::string name)
509         { m_player_names.push_back(name); }
510         void removePlayerName(std::string name)
511         { m_player_names.remove(name); }
512         void updateCameraOffset(v3s16 camera_offset)
513         { m_camera_offset = camera_offset; }
514         v3s16 getCameraOffset()
515         { return m_camera_offset; }
516
517 private:
518         ClientMap *m_map;
519         scene::ISceneManager *m_smgr;
520         ITextureSource *m_texturesource;
521         IGameDef *m_gamedef;
522         IrrlichtDevice *m_irr;
523         std::map<u16, ClientActiveObject*> m_active_objects;
524         std::vector<ClientSimpleObject*> m_simple_objects;
525         std::list<ClientEnvEvent> m_client_event_queue;
526         IntervalLimiter m_active_object_light_update_interval;
527         IntervalLimiter m_lava_hurt_interval;
528         IntervalLimiter m_drowning_interval;
529         IntervalLimiter m_breathing_interval;
530         std::list<std::string> m_player_names;
531         v3s16 m_camera_offset;
532 };
533
534 #endif
535
536 #endif
537