3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #ifndef ENVIRONMENT_HEADER
21 #define ENVIRONMENT_HEADER
24 This class is the game's environment.
29 - The current time in the game
38 #include "activeobject.h"
39 #include "util/numeric.h"
42 #include "threading/mutex.h"
43 #include "threading/atomic.h"
44 #include "network/networkprotocol.h" // for AccessDeniedCode
46 class ServerEnvironment;
47 class ActiveBlockModifier;
48 class ServerActiveObject;
61 // Environment will delete the map passed to the constructor
63 virtual ~Environment();
66 Step everything in environment.
71 virtual void step(f32 dtime) = 0;
73 virtual Map & getMap() = 0;
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);
84 u32 getDayNightRatio();
87 virtual void setTimeOfDay(u32 time);
89 float getTimeOfDayF();
91 void stepTimeOfDay(float dtime);
93 void setTimeOfDaySpeed(float speed);
94 float getTimeOfDaySpeed();
96 void setDayNightRatioOverride(bool enable, u32 value);
100 // counter used internally when triggering ABMs
104 // peer_ids in here should be unique, except that there may be many 0s
105 std::vector<Player*> m_players;
107 GenericAtomic<float> m_time_of_day_speed;
110 * Below: values managed by m_time_lock
112 // Time of day in milli-hours (0-23999); determines day and night
114 // Time of day in 0...1
115 float m_time_of_day_f;
116 // Stores the skew created by the float -> u32 conversion
117 // to be applied at next conversion, so that there is no real skew.
118 float m_time_conversion_skew;
119 // Overriding the day-night ratio is useful for custom sky visuals
120 bool m_enable_day_night_ratio_override;
121 u32 m_day_night_ratio_override;
122 // Days from the server start, accounts for time shift
123 // in game (e.g. /time or bed usage)
124 Atomic<u32> m_day_count;
126 * Above: values managed by m_time_lock
129 /* TODO: Add a callback function so these can be updated when a setting
130 * changes. At this point in time it doesn't matter (e.g. /set
131 * is documented to change server settings only)
133 * TODO: Local caching of settings is not optimal and should at some stage
134 * be updated to use a global settings object for getting thse values
135 * (as opposed to the this local caching). This can be addressed in
138 bool m_cache_enable_shaders;
139 float m_cache_active_block_mgmt_interval;
140 float m_cache_abm_interval;
141 float m_cache_nodetimer_interval;
146 DISABLE_CLASS_COPY(Environment);
150 {Active, Loading} block modifier interface.
152 These are fed into ServerEnvironment at initialization time;
153 ServerEnvironment handles deleting them.
156 class ActiveBlockModifier
159 ActiveBlockModifier(){};
160 virtual ~ActiveBlockModifier(){};
162 // Set of contents to trigger on
163 virtual std::set<std::string> getTriggerContents()=0;
164 // Set of required neighbors (trigger doesn't happen if none are found)
165 // Empty = do not check neighbors
166 virtual std::set<std::string> getRequiredNeighbors()
167 { return std::set<std::string>(); }
168 // Trigger interval in seconds
169 virtual float getTriggerInterval() = 0;
170 // Random chance of (1 / return value), 0 is disallowed
171 virtual u32 getTriggerChance() = 0;
172 // Whether to modify chance to simulate time lost by an unnattended block
173 virtual bool getSimpleCatchUp() = 0;
174 // This is called usually at interval for 1/chance of the nodes
175 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
176 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
177 u32 active_object_count, u32 active_object_count_wider){};
182 ActiveBlockModifier *abm;
185 ABMWithState(ActiveBlockModifier *abm_);
188 struct LoadingBlockModifierDef
190 // Set of contents to trigger on
191 std::set<std::string> trigger_contents;
193 bool run_at_every_load;
195 virtual ~LoadingBlockModifierDef() {}
196 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
199 struct LBMContentMapping
201 typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
204 std::vector<LoadingBlockModifierDef *> lbm_list;
206 // Needs to be separate method (not inside destructor),
207 // because the LBMContentMapping may be copied and destructed
208 // many times during operation in the lbm_lookup_map.
209 void deleteContents();
210 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
211 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
223 // Don't call this after loadIntroductionTimes() ran.
224 void addLBMDef(LoadingBlockModifierDef *lbm_def);
226 void loadIntroductionTimes(const std::string ×,
227 IGameDef *gamedef, u32 now);
229 // Don't call this before loadIntroductionTimes() ran.
230 std::string createIntroductionTimesString();
232 // Don't call this before loadIntroductionTimes() ran.
233 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
235 // Warning: do not make this std::unordered_map, order is relevant here
236 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
239 // Once we set this to true, we can only query,
243 // For m_query_mode == false:
244 // The key of the map is the LBM def's name.
245 // TODO make this std::unordered_map
246 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
248 // For m_query_mode == true:
249 // The key of the map is the LBM def's first introduction time.
250 lbm_lookup_map m_lbm_lookup;
252 // Returns an iterator to the LBMs that were introduced
253 // after the given time. This is guaranteed to return
254 // valid values for everything
255 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
256 { return m_lbm_lookup.lower_bound(time); }
260 List of active blocks, used by ServerEnvironment
263 class ActiveBlockList
266 void update(std::vector<v3s16> &active_positions,
268 std::set<v3s16> &blocks_removed,
269 std::set<v3s16> &blocks_added);
271 bool contains(v3s16 p){
272 return (m_list.find(p) != m_list.end());
279 std::set<v3s16> m_list;
280 std::set<v3s16> m_forceloaded_list;
286 Operation mode for ServerEnvironment::clearObjects()
288 enum ClearObjectsMode {
289 // Load and go through every mapblock, clearing objects
290 CLEAR_OBJECTS_MODE_FULL,
292 // Clear objects immediately in loaded mapblocks;
293 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
294 CLEAR_OBJECTS_MODE_QUICK,
298 The server-side environment.
300 This is not thread-safe. Server uses an environment mutex.
303 class ServerEnvironment : public Environment
306 ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
307 IGameDef *gamedef, const std::string &path_world);
308 ~ServerEnvironment();
312 ServerMap & getServerMap();
314 //TODO find way to remove this fct!
315 GameScripting* getScriptIface()
318 IGameDef *getGameDef()
319 { return m_gamedef; }
321 float getSendRecommendedInterval()
322 { return m_recommended_send_interval; }
324 void kickAllPlayers(AccessDeniedCode reason,
325 const std::string &str_reason, bool reconnect);
327 void saveLoadedPlayers();
328 void savePlayer(RemotePlayer *player);
329 Player *loadPlayer(const std::string &playername);
332 Save and load time of day and game timer
336 // to be called instead of loadMeta if
337 // env_meta.txt doesn't exist (e.g. new world)
338 void loadDefaultMeta();
341 External ActiveObject interface
342 -------------------------------------------
345 ServerActiveObject* getActiveObject(u16 id);
348 Add an active object to the environment.
349 Environment handles deletion of object.
350 Object may be deleted by environment immediately.
351 If id of object is 0, assigns a free id to it.
352 Returns the id of the object.
353 Returns 0 if not added and thus deleted.
355 u16 addActiveObject(ServerActiveObject *object);
358 Add an active object as a static object to the corresponding
360 Caller allocates memory, ServerEnvironment frees memory.
361 Return value: true if succeeded, false if failed.
362 (note: not used, pending removal from engine)
364 //bool addActiveObjectAsStatic(ServerActiveObject *object);
367 Find out what new objects have been added to
368 inside a radius around a position
370 void getAddedActiveObjects(Player *player, s16 radius,
372 std::set<u16> ¤t_objects,
373 std::queue<u16> &added_objects);
376 Find out what new objects have been removed from
377 inside a radius around a position
379 void getRemovedActiveObjects(Player* player, s16 radius,
381 std::set<u16> ¤t_objects,
382 std::queue<u16> &removed_objects);
385 Get the next message emitted by some active object.
386 Returns a message with id=0 if no messages are available.
388 ActiveObjectMessage getActiveObjectMessage();
391 Activate objects and dynamically modify for the dtime determined
392 from timestamp and additional_dtime
394 void activateBlock(MapBlock *block, u32 additional_dtime=0);
397 {Active,Loading}BlockModifiers
398 -------------------------------------------
401 void addActiveBlockModifier(ActiveBlockModifier *abm);
402 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
406 -------------------------------------------
409 // Script-aware node setters
410 bool setNode(v3s16 p, const MapNode &n);
411 bool removeNode(v3s16 p);
412 bool swapNode(v3s16 p, const MapNode &n);
414 // Find all active objects inside a radius around a point
415 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
417 // Clear objects, loading and going through every MapBlock
418 void clearObjects(ClearObjectsMode mode);
420 // This makes stuff happen
421 void step(f32 dtime);
423 //check if there's a line of sight between two positions
424 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
426 u32 getGameTime() { return m_game_time; }
428 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
429 float getMaxLagEstimate() { return m_max_lag_estimate; }
431 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
433 // Sets the static object status all the active objects in the specified block
434 // This is only really needed for deleting blocks from the map
435 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
436 bool static_exists, v3s16 static_block=v3s16(0,0,0));
441 Internal ActiveObject interface
442 -------------------------------------------
446 Add an active object to the environment.
448 Called by addActiveObject.
450 Object may be deleted by environment immediately.
451 If id of object is 0, assigns a free id to it.
452 Returns the id of the object.
453 Returns 0 if not added and thus deleted.
455 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
458 Remove all objects that satisfy (m_removed && m_known_by_count==0)
460 void removeRemovedObjects();
463 Convert stored objects from block to active
465 void activateObjects(MapBlock *block, u32 dtime_s);
468 Convert objects that are not in active blocks to static.
470 If m_known_by_count != 0, active object is not deleted, but static
471 data is still updated.
473 If force_delete is set, active object is deleted nevertheless. It
474 shall only be set so in the destructor of the environment.
476 void deactivateFarObjects(bool force_delete);
485 GameScripting* m_script;
489 const std::string m_path_world;
490 // Active object list
491 std::map<u16, ServerActiveObject*> m_active_objects;
492 // Outgoing network message buffer for active objects
493 std::queue<ActiveObjectMessage> m_active_object_messages;
495 float m_send_recommended_timer;
496 IntervalLimiter m_object_management_interval;
497 // List of active blocks
498 ActiveBlockList m_active_blocks;
499 IntervalLimiter m_active_blocks_management_interval;
500 IntervalLimiter m_active_block_modifier_interval;
501 IntervalLimiter m_active_blocks_nodemetadata_interval;
502 int m_active_block_interval_overload_skip;
503 // Time from the beginning of the game in seconds.
504 // Incremented in step().
506 // A helper variable for incrementing the latter
507 float m_game_time_fraction_counter;
508 // Time of last clearObjects call (game time).
509 // When a mapblock older than this is loaded, its objects are cleared.
510 u32 m_last_clear_objects_time;
511 // Active block modifiers
512 std::vector<ABMWithState> m_abms;
513 LBMManager m_lbm_mgr;
514 // An interval for generally sending object positions and stuff
515 float m_recommended_send_interval;
516 // Estimate for general maximum lag as determined by server.
517 // Can raise to high values like 15s with eg. map generation mods.
518 float m_max_lag_estimate;
523 #include "clientobject.h"
524 #include "content_cao.h"
526 class ClientSimpleObject;
529 The client-side environment.
531 This is not thread-safe.
532 Must be called from main (irrlicht) thread (uses the SceneManager)
533 Client uses an environment mutex.
536 enum ClientEnvEventType
543 struct ClientEnvEvent
545 ClientEnvEventType type;
559 class ClientEnvironment : public Environment
562 ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
563 ITextureSource *texturesource, IGameDef *gamedef,
564 IrrlichtDevice *device);
565 ~ClientEnvironment();
568 ClientMap & getClientMap();
570 IGameDef *getGameDef()
571 { return m_gamedef; }
573 void step(f32 dtime);
575 virtual void addPlayer(Player *player);
576 LocalPlayer * getLocalPlayer();
582 void addSimpleObject(ClientSimpleObject *simple);
588 GenericCAO* getGenericCAO(u16 id);
589 ClientActiveObject* getActiveObject(u16 id);
592 Adds an active object to the environment.
593 Environment handles deletion of object.
594 Object may be deleted by environment immediately.
595 If id of object is 0, assigns a free id to it.
596 Returns the id of the object.
597 Returns 0 if not added and thus deleted.
599 u16 addActiveObject(ClientActiveObject *object);
601 void addActiveObject(u16 id, u8 type, const std::string &init_data);
602 void removeActiveObject(u16 id);
604 void processActiveObjectMessage(u16 id, const std::string &data);
607 Callbacks for activeobjects
610 void damageLocalPlayer(u8 damage, bool handle_hp=true);
611 void updateLocalPlayerBreath(u16 breath);
614 Client likes to call these
617 // Get all nearby objects
618 void getActiveObjects(v3f origin, f32 max_d,
619 std::vector<DistanceSortedActiveObject> &dest);
621 // Get event from queue. CEE_NONE is returned if queue is empty.
622 ClientEnvEvent getClientEvent();
624 u16 attachement_parent_ids[USHRT_MAX + 1];
626 std::list<std::string> getPlayerNames()
627 { return m_player_names; }
628 void addPlayerName(std::string name)
629 { m_player_names.push_back(name); }
630 void removePlayerName(std::string name)
631 { m_player_names.remove(name); }
632 void updateCameraOffset(v3s16 camera_offset)
633 { m_camera_offset = camera_offset; }
634 v3s16 getCameraOffset()
635 { return m_camera_offset; }
639 scene::ISceneManager *m_smgr;
640 ITextureSource *m_texturesource;
642 IrrlichtDevice *m_irr;
643 std::map<u16, ClientActiveObject*> m_active_objects;
644 std::vector<ClientSimpleObject*> m_simple_objects;
645 std::queue<ClientEnvEvent> m_client_event_queue;
646 IntervalLimiter m_active_object_light_update_interval;
647 IntervalLimiter m_lava_hurt_interval;
648 IntervalLimiter m_drowning_interval;
649 IntervalLimiter m_breathing_interval;
650 std::list<std::string> m_player_names;
651 v3s16 m_camera_offset;