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