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;
62 // Environment will delete the map passed to the constructor
64 virtual ~Environment();
67 Step everything in environment.
72 virtual void step(f32 dtime) = 0;
74 virtual Map & getMap() = 0;
76 u32 getDayNightRatio();
79 virtual void setTimeOfDay(u32 time);
81 float getTimeOfDayF();
83 void stepTimeOfDay(float dtime);
85 void setTimeOfDaySpeed(float speed);
87 void setDayNightRatioOverride(bool enable, u32 value);
91 // counter used internally when triggering ABMs
95 GenericAtomic<float> m_time_of_day_speed;
98 * Below: values managed by m_time_lock
100 // Time of day in milli-hours (0-23999); determines day and night
102 // Time of day in 0...1
103 float m_time_of_day_f;
104 // Stores the skew created by the float -> u32 conversion
105 // to be applied at next conversion, so that there is no real skew.
106 float m_time_conversion_skew;
107 // Overriding the day-night ratio is useful for custom sky visuals
108 bool m_enable_day_night_ratio_override;
109 u32 m_day_night_ratio_override;
110 // Days from the server start, accounts for time shift
111 // in game (e.g. /time or bed usage)
112 Atomic<u32> m_day_count;
114 * Above: values managed by m_time_lock
117 /* TODO: Add a callback function so these can be updated when a setting
118 * changes. At this point in time it doesn't matter (e.g. /set
119 * is documented to change server settings only)
121 * TODO: Local caching of settings is not optimal and should at some stage
122 * be updated to use a global settings object for getting thse values
123 * (as opposed to the this local caching). This can be addressed in
126 bool m_cache_enable_shaders;
127 float m_cache_active_block_mgmt_interval;
128 float m_cache_abm_interval;
129 float m_cache_nodetimer_interval;
134 DISABLE_CLASS_COPY(Environment);
138 {Active, Loading} block modifier interface.
140 These are fed into ServerEnvironment at initialization time;
141 ServerEnvironment handles deleting them.
144 class ActiveBlockModifier
147 ActiveBlockModifier(){};
148 virtual ~ActiveBlockModifier(){};
150 // Set of contents to trigger on
151 virtual std::set<std::string> getTriggerContents()=0;
152 // Set of required neighbors (trigger doesn't happen if none are found)
153 // Empty = do not check neighbors
154 virtual std::set<std::string> getRequiredNeighbors()
155 { return std::set<std::string>(); }
156 // Trigger interval in seconds
157 virtual float getTriggerInterval() = 0;
158 // Random chance of (1 / return value), 0 is disallowed
159 virtual u32 getTriggerChance() = 0;
160 // Whether to modify chance to simulate time lost by an unnattended block
161 virtual bool getSimpleCatchUp() = 0;
162 // This is called usually at interval for 1/chance of the nodes
163 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
164 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
165 u32 active_object_count, u32 active_object_count_wider){};
170 ActiveBlockModifier *abm;
173 ABMWithState(ActiveBlockModifier *abm_);
176 struct LoadingBlockModifierDef
178 // Set of contents to trigger on
179 std::set<std::string> trigger_contents;
181 bool run_at_every_load;
183 virtual ~LoadingBlockModifierDef() {}
184 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
187 struct LBMContentMapping
189 typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
192 std::vector<LoadingBlockModifierDef *> lbm_list;
194 // Needs to be separate method (not inside destructor),
195 // because the LBMContentMapping may be copied and destructed
196 // many times during operation in the lbm_lookup_map.
197 void deleteContents();
198 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
199 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
211 // Don't call this after loadIntroductionTimes() ran.
212 void addLBMDef(LoadingBlockModifierDef *lbm_def);
214 void loadIntroductionTimes(const std::string ×,
215 IGameDef *gamedef, u32 now);
217 // Don't call this before loadIntroductionTimes() ran.
218 std::string createIntroductionTimesString();
220 // Don't call this before loadIntroductionTimes() ran.
221 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
223 // Warning: do not make this std::unordered_map, order is relevant here
224 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
227 // Once we set this to true, we can only query,
231 // For m_query_mode == false:
232 // The key of the map is the LBM def's name.
233 // TODO make this std::unordered_map
234 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
236 // For m_query_mode == true:
237 // The key of the map is the LBM def's first introduction time.
238 lbm_lookup_map m_lbm_lookup;
240 // Returns an iterator to the LBMs that were introduced
241 // after the given time. This is guaranteed to return
242 // valid values for everything
243 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
244 { return m_lbm_lookup.lower_bound(time); }
248 List of active blocks, used by ServerEnvironment
251 class ActiveBlockList
254 void update(std::vector<v3s16> &active_positions,
256 std::set<v3s16> &blocks_removed,
257 std::set<v3s16> &blocks_added);
259 bool contains(v3s16 p){
260 return (m_list.find(p) != m_list.end());
267 std::set<v3s16> m_list;
268 std::set<v3s16> m_forceloaded_list;
274 Operation mode for ServerEnvironment::clearObjects()
276 enum ClearObjectsMode {
277 // Load and go through every mapblock, clearing objects
278 CLEAR_OBJECTS_MODE_FULL,
280 // Clear objects immediately in loaded mapblocks;
281 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
282 CLEAR_OBJECTS_MODE_QUICK,
286 The server-side environment.
288 This is not thread-safe. Server uses an environment mutex.
291 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
293 class ServerEnvironment : public Environment
296 ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
297 IGameDef *gamedef, const std::string &path_world);
298 ~ServerEnvironment();
302 ServerMap & getServerMap();
304 //TODO find way to remove this fct!
305 GameScripting* getScriptIface()
308 IGameDef *getGameDef()
309 { return m_gamedef; }
311 float getSendRecommendedInterval()
312 { return m_recommended_send_interval; }
314 void kickAllPlayers(AccessDeniedCode reason,
315 const std::string &str_reason, bool reconnect);
317 void saveLoadedPlayers();
318 void savePlayer(RemotePlayer *player);
319 RemotePlayer *loadPlayer(const std::string &playername, PlayerSAO *sao);
320 void addPlayer(RemotePlayer *player);
321 void removePlayer(RemotePlayer *player);
324 Save and load time of day and game timer
328 // to be called instead of loadMeta if
329 // env_meta.txt doesn't exist (e.g. new world)
330 void loadDefaultMeta();
332 u32 addParticleSpawner(float exptime);
333 u32 addParticleSpawner(float exptime, u16 attached_id);
334 void deleteParticleSpawner(u32 id, bool remove_from_object = true);
337 External ActiveObject interface
338 -------------------------------------------
341 ServerActiveObject* getActiveObject(u16 id);
344 Add an active object to the environment.
345 Environment handles deletion of object.
346 Object may be deleted by environment immediately.
347 If id of object is 0, assigns a free id to it.
348 Returns the id of the object.
349 Returns 0 if not added and thus deleted.
351 u16 addActiveObject(ServerActiveObject *object);
354 Add an active object as a static object to the corresponding
356 Caller allocates memory, ServerEnvironment frees memory.
357 Return value: true if succeeded, false if failed.
358 (note: not used, pending removal from engine)
360 //bool addActiveObjectAsStatic(ServerActiveObject *object);
363 Find out what new objects have been added to
364 inside a radius around a position
366 void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
368 std::set<u16> ¤t_objects,
369 std::queue<u16> &added_objects);
372 Find out what new objects have been removed from
373 inside a radius around a position
375 void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
377 std::set<u16> ¤t_objects,
378 std::queue<u16> &removed_objects);
381 Get the next message emitted by some active object.
382 Returns a message with id=0 if no messages are available.
384 ActiveObjectMessage getActiveObjectMessage();
387 Activate objects and dynamically modify for the dtime determined
388 from timestamp and additional_dtime
390 void activateBlock(MapBlock *block, u32 additional_dtime=0);
393 {Active,Loading}BlockModifiers
394 -------------------------------------------
397 void addActiveBlockModifier(ActiveBlockModifier *abm);
398 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
402 -------------------------------------------
405 // Script-aware node setters
406 bool setNode(v3s16 p, const MapNode &n);
407 bool removeNode(v3s16 p);
408 bool swapNode(v3s16 p, const MapNode &n);
410 // Find all active objects inside a radius around a point
411 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
413 // Clear objects, loading and going through every MapBlock
414 void clearObjects(ClearObjectsMode mode);
416 // This makes stuff happen
417 void step(f32 dtime);
419 //check if there's a line of sight between two positions
420 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
422 u32 getGameTime() { return m_game_time; }
424 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
425 float getMaxLagEstimate() { return m_max_lag_estimate; }
427 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
429 // Sets the static object status all the active objects in the specified block
430 // This is only really needed for deleting blocks from the map
431 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
432 bool static_exists, v3s16 static_block=v3s16(0,0,0));
434 RemotePlayer *getPlayer(const u16 peer_id);
435 RemotePlayer *getPlayer(const char* name);
439 Internal ActiveObject interface
440 -------------------------------------------
444 Add an active object to the environment.
446 Called by addActiveObject.
448 Object may be deleted by environment immediately.
449 If id of object is 0, assigns a free id to it.
450 Returns the id of the object.
451 Returns 0 if not added and thus deleted.
453 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
456 Remove all objects that satisfy (m_removed && m_known_by_count==0)
458 void removeRemovedObjects();
461 Convert stored objects from block to active
463 void activateObjects(MapBlock *block, u32 dtime_s);
466 Convert objects that are not in active blocks to static.
468 If m_known_by_count != 0, active object is not deleted, but static
469 data is still updated.
471 If force_delete is set, active object is deleted nevertheless. It
472 shall only be set so in the destructor of the environment.
474 void deactivateFarObjects(bool force_delete);
483 GameScripting* m_script;
487 const std::string m_path_world;
488 // Active object list
489 ActiveObjectMap m_active_objects;
490 // Outgoing network message buffer for active objects
491 std::queue<ActiveObjectMessage> m_active_object_messages;
493 float m_send_recommended_timer;
494 IntervalLimiter m_object_management_interval;
495 // List of active blocks
496 ActiveBlockList m_active_blocks;
497 IntervalLimiter m_active_blocks_management_interval;
498 IntervalLimiter m_active_block_modifier_interval;
499 IntervalLimiter m_active_blocks_nodemetadata_interval;
500 int m_active_block_interval_overload_skip;
501 // Time from the beginning of the game in seconds.
502 // Incremented in step().
504 // A helper variable for incrementing the latter
505 float m_game_time_fraction_counter;
506 // Time of last clearObjects call (game time).
507 // When a mapblock older than this is loaded, its objects are cleared.
508 u32 m_last_clear_objects_time;
509 // Active block modifiers
510 std::vector<ABMWithState> m_abms;
511 LBMManager m_lbm_mgr;
512 // An interval for generally sending object positions and stuff
513 float m_recommended_send_interval;
514 // Estimate for general maximum lag as determined by server.
515 // Can raise to high values like 15s with eg. map generation mods.
516 float m_max_lag_estimate;
518 // peer_ids in here should be unique, except that there may be many 0s
519 std::vector<RemotePlayer*> m_players;
522 IntervalLimiter m_particle_management_interval;
523 UNORDERED_MAP<u32, float> m_particle_spawners;
524 UNORDERED_MAP<u32, u16> m_particle_spawner_attachments;
529 #include "clientobject.h"
530 #include "content_cao.h"
532 class ClientSimpleObject;
535 The client-side environment.
537 This is not thread-safe.
538 Must be called from main (irrlicht) thread (uses the SceneManager)
539 Client uses an environment mutex.
542 enum ClientEnvEventType
549 struct ClientEnvEvent
551 ClientEnvEventType type;
565 class ClientEnvironment : public Environment
568 ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
569 ITextureSource *texturesource, IGameDef *gamedef,
570 IrrlichtDevice *device);
571 ~ClientEnvironment();
574 ClientMap & getClientMap();
576 IGameDef *getGameDef()
577 { return m_gamedef; }
579 void step(f32 dtime);
581 virtual void setLocalPlayer(LocalPlayer *player);
582 LocalPlayer *getLocalPlayer() { return m_local_player; }
588 void addSimpleObject(ClientSimpleObject *simple);
594 GenericCAO* getGenericCAO(u16 id);
595 ClientActiveObject* getActiveObject(u16 id);
598 Adds an active object to the environment.
599 Environment handles deletion of object.
600 Object may be deleted by environment immediately.
601 If id of object is 0, assigns a free id to it.
602 Returns the id of the object.
603 Returns 0 if not added and thus deleted.
605 u16 addActiveObject(ClientActiveObject *object);
607 void addActiveObject(u16 id, u8 type, const std::string &init_data);
608 void removeActiveObject(u16 id);
610 void processActiveObjectMessage(u16 id, const std::string &data);
613 Callbacks for activeobjects
616 void damageLocalPlayer(u8 damage, bool handle_hp=true);
617 void updateLocalPlayerBreath(u16 breath);
620 Client likes to call these
623 // Get all nearby objects
624 void getActiveObjects(v3f origin, f32 max_d,
625 std::vector<DistanceSortedActiveObject> &dest);
627 // Get event from queue. CEE_NONE is returned if queue is empty.
628 ClientEnvEvent getClientEvent();
630 u16 attachement_parent_ids[USHRT_MAX + 1];
632 const std::list<std::string> &getPlayerNames() { return m_player_names; }
633 void addPlayerName(const std::string &name) { m_player_names.push_back(name); }
634 void removePlayerName(const std::string &name) { m_player_names.remove(name); }
635 void updateCameraOffset(v3s16 camera_offset)
636 { m_camera_offset = camera_offset; }
637 v3s16 getCameraOffset() const { return m_camera_offset; }
640 LocalPlayer *m_local_player;
641 scene::ISceneManager *m_smgr;
642 ITextureSource *m_texturesource;
644 IrrlichtDevice *m_irr;
645 UNORDERED_MAP<u16, ClientActiveObject*> m_active_objects;
646 std::vector<ClientSimpleObject*> m_simple_objects;
647 std::queue<ClientEnvEvent> m_client_event_queue;
648 IntervalLimiter m_active_object_light_update_interval;
649 IntervalLimiter m_lava_hurt_interval;
650 IntervalLimiter m_drowning_interval;
651 IntervalLimiter m_breathing_interval;
652 std::list<std::string> m_player_names;
653 v3s16 m_camera_offset;