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;
63 // Environment will delete the map passed to the constructor
65 virtual ~Environment();
68 Step everything in environment.
73 virtual void step(f32 dtime) = 0;
75 virtual Map & getMap() = 0;
77 u32 getDayNightRatio();
80 virtual void setTimeOfDay(u32 time);
82 float getTimeOfDayF();
84 void stepTimeOfDay(float dtime);
86 void setTimeOfDaySpeed(float speed);
88 void setDayNightRatioOverride(bool enable, u32 value);
92 // counter used internally when triggering ABMs
96 GenericAtomic<float> m_time_of_day_speed;
99 * Below: values managed by m_time_lock
101 // Time of day in milli-hours (0-23999); determines day and night
103 // Time of day in 0...1
104 float m_time_of_day_f;
105 // Stores the skew created by the float -> u32 conversion
106 // to be applied at next conversion, so that there is no real skew.
107 float m_time_conversion_skew;
108 // Overriding the day-night ratio is useful for custom sky visuals
109 bool m_enable_day_night_ratio_override;
110 u32 m_day_night_ratio_override;
111 // Days from the server start, accounts for time shift
112 // in game (e.g. /time or bed usage)
113 Atomic<u32> m_day_count;
115 * Above: values managed by m_time_lock
118 /* TODO: Add a callback function so these can be updated when a setting
119 * changes. At this point in time it doesn't matter (e.g. /set
120 * is documented to change server settings only)
122 * TODO: Local caching of settings is not optimal and should at some stage
123 * be updated to use a global settings object for getting thse values
124 * (as opposed to the this local caching). This can be addressed in
127 bool m_cache_enable_shaders;
128 float m_cache_active_block_mgmt_interval;
129 float m_cache_abm_interval;
130 float m_cache_nodetimer_interval;
135 DISABLE_CLASS_COPY(Environment);
139 {Active, Loading} block modifier interface.
141 These are fed into ServerEnvironment at initialization time;
142 ServerEnvironment handles deleting them.
145 class ActiveBlockModifier
148 ActiveBlockModifier(){};
149 virtual ~ActiveBlockModifier(){};
151 // Set of contents to trigger on
152 virtual std::set<std::string> getTriggerContents()=0;
153 // Set of required neighbors (trigger doesn't happen if none are found)
154 // Empty = do not check neighbors
155 virtual std::set<std::string> getRequiredNeighbors()
156 { return std::set<std::string>(); }
157 // Trigger interval in seconds
158 virtual float getTriggerInterval() = 0;
159 // Random chance of (1 / return value), 0 is disallowed
160 virtual u32 getTriggerChance() = 0;
161 // Whether to modify chance to simulate time lost by an unnattended block
162 virtual bool getSimpleCatchUp() = 0;
163 // This is called usually at interval for 1/chance of the nodes
164 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
165 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
166 u32 active_object_count, u32 active_object_count_wider){};
171 ActiveBlockModifier *abm;
174 ABMWithState(ActiveBlockModifier *abm_);
177 struct LoadingBlockModifierDef
179 // Set of contents to trigger on
180 std::set<std::string> trigger_contents;
182 bool run_at_every_load;
184 virtual ~LoadingBlockModifierDef() {}
185 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
188 struct LBMContentMapping
190 typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
193 std::vector<LoadingBlockModifierDef *> lbm_list;
195 // Needs to be separate method (not inside destructor),
196 // because the LBMContentMapping may be copied and destructed
197 // many times during operation in the lbm_lookup_map.
198 void deleteContents();
199 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
200 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
212 // Don't call this after loadIntroductionTimes() ran.
213 void addLBMDef(LoadingBlockModifierDef *lbm_def);
215 void loadIntroductionTimes(const std::string ×,
216 IGameDef *gamedef, u32 now);
218 // Don't call this before loadIntroductionTimes() ran.
219 std::string createIntroductionTimesString();
221 // Don't call this before loadIntroductionTimes() ran.
222 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
224 // Warning: do not make this std::unordered_map, order is relevant here
225 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
228 // Once we set this to true, we can only query,
232 // For m_query_mode == false:
233 // The key of the map is the LBM def's name.
234 // TODO make this std::unordered_map
235 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
237 // For m_query_mode == true:
238 // The key of the map is the LBM def's first introduction time.
239 lbm_lookup_map m_lbm_lookup;
241 // Returns an iterator to the LBMs that were introduced
242 // after the given time. This is guaranteed to return
243 // valid values for everything
244 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
245 { return m_lbm_lookup.lower_bound(time); }
249 List of active blocks, used by ServerEnvironment
252 class ActiveBlockList
255 void update(std::vector<v3s16> &active_positions,
257 std::set<v3s16> &blocks_removed,
258 std::set<v3s16> &blocks_added);
260 bool contains(v3s16 p){
261 return (m_list.find(p) != m_list.end());
268 std::set<v3s16> m_list;
269 std::set<v3s16> m_forceloaded_list;
275 Operation mode for ServerEnvironment::clearObjects()
277 enum ClearObjectsMode {
278 // Load and go through every mapblock, clearing objects
279 CLEAR_OBJECTS_MODE_FULL,
281 // Clear objects immediately in loaded mapblocks;
282 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
283 CLEAR_OBJECTS_MODE_QUICK,
287 The server-side environment.
289 This is not thread-safe. Server uses an environment mutex.
292 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
294 class ServerEnvironment : public Environment
297 ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
298 IGameDef *gamedef, const std::string &path_world);
299 ~ServerEnvironment();
303 ServerMap & getServerMap();
305 //TODO find way to remove this fct!
306 GameScripting* getScriptIface()
309 IGameDef *getGameDef()
310 { return m_gamedef; }
312 float getSendRecommendedInterval()
313 { return m_recommended_send_interval; }
315 void kickAllPlayers(AccessDeniedCode reason,
316 const std::string &str_reason, bool reconnect);
318 void saveLoadedPlayers();
319 void savePlayer(RemotePlayer *player);
320 RemotePlayer *loadPlayer(const std::string &playername, PlayerSAO *sao);
321 void addPlayer(RemotePlayer *player);
322 void removePlayer(RemotePlayer *player);
325 Save and load time of day and game timer
329 // to be called instead of loadMeta if
330 // env_meta.txt doesn't exist (e.g. new world)
331 void loadDefaultMeta();
333 u32 addParticleSpawner(float exptime);
334 u32 addParticleSpawner(float exptime, u16 attached_id);
335 void deleteParticleSpawner(u32 id, bool remove_from_object = true);
338 External ActiveObject interface
339 -------------------------------------------
342 ServerActiveObject* getActiveObject(u16 id);
345 Add an active object to the environment.
346 Environment handles deletion of object.
347 Object may be deleted by environment immediately.
348 If id of object is 0, assigns a free id to it.
349 Returns the id of the object.
350 Returns 0 if not added and thus deleted.
352 u16 addActiveObject(ServerActiveObject *object);
355 Add an active object as a static object to the corresponding
357 Caller allocates memory, ServerEnvironment frees memory.
358 Return value: true if succeeded, false if failed.
359 (note: not used, pending removal from engine)
361 //bool addActiveObjectAsStatic(ServerActiveObject *object);
364 Find out what new objects have been added to
365 inside a radius around a position
367 void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
369 std::set<u16> ¤t_objects,
370 std::queue<u16> &added_objects);
373 Find out what new objects have been removed from
374 inside a radius around a position
376 void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
378 std::set<u16> ¤t_objects,
379 std::queue<u16> &removed_objects);
382 Get the next message emitted by some active object.
383 Returns a message with id=0 if no messages are available.
385 ActiveObjectMessage getActiveObjectMessage();
388 Activate objects and dynamically modify for the dtime determined
389 from timestamp and additional_dtime
391 void activateBlock(MapBlock *block, u32 additional_dtime=0);
394 {Active,Loading}BlockModifiers
395 -------------------------------------------
398 void addActiveBlockModifier(ActiveBlockModifier *abm);
399 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
403 -------------------------------------------
406 // Script-aware node setters
407 bool setNode(v3s16 p, const MapNode &n);
408 bool removeNode(v3s16 p);
409 bool swapNode(v3s16 p, const MapNode &n);
411 // Find all active objects inside a radius around a point
412 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
414 // Clear objects, loading and going through every MapBlock
415 void clearObjects(ClearObjectsMode mode);
417 // This makes stuff happen
418 void step(f32 dtime);
420 //check if there's a line of sight between two positions
421 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
423 u32 getGameTime() { return m_game_time; }
425 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
426 float getMaxLagEstimate() { return m_max_lag_estimate; }
428 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
430 // Sets the static object status all the active objects in the specified block
431 // This is only really needed for deleting blocks from the map
432 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
433 bool static_exists, v3s16 static_block=v3s16(0,0,0));
435 RemotePlayer *getPlayer(const u16 peer_id);
436 RemotePlayer *getPlayer(const char* name);
440 Internal ActiveObject interface
441 -------------------------------------------
445 Add an active object to the environment.
447 Called by addActiveObject.
449 Object may be deleted by environment immediately.
450 If id of object is 0, assigns a free id to it.
451 Returns the id of the object.
452 Returns 0 if not added and thus deleted.
454 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
457 Remove all objects that satisfy (m_removed && m_known_by_count==0)
459 void removeRemovedObjects();
462 Convert stored objects from block to active
464 void activateObjects(MapBlock *block, u32 dtime_s);
467 Convert objects that are not in active blocks to static.
469 If m_known_by_count != 0, active object is not deleted, but static
470 data is still updated.
472 If force_delete is set, active object is deleted nevertheless. It
473 shall only be set so in the destructor of the environment.
475 void deactivateFarObjects(bool force_delete);
484 GameScripting* m_script;
488 const std::string m_path_world;
489 // Active object list
490 ActiveObjectMap m_active_objects;
491 // Outgoing network message buffer for active objects
492 std::queue<ActiveObjectMessage> m_active_object_messages;
494 float m_send_recommended_timer;
495 IntervalLimiter m_object_management_interval;
496 // List of active blocks
497 ActiveBlockList m_active_blocks;
498 IntervalLimiter m_active_blocks_management_interval;
499 IntervalLimiter m_active_block_modifier_interval;
500 IntervalLimiter m_active_blocks_nodemetadata_interval;
501 int m_active_block_interval_overload_skip;
502 // Time from the beginning of the game in seconds.
503 // Incremented in step().
505 // A helper variable for incrementing the latter
506 float m_game_time_fraction_counter;
507 // Time of last clearObjects call (game time).
508 // When a mapblock older than this is loaded, its objects are cleared.
509 u32 m_last_clear_objects_time;
510 // Active block modifiers
511 std::vector<ABMWithState> m_abms;
512 LBMManager m_lbm_mgr;
513 // An interval for generally sending object positions and stuff
514 float m_recommended_send_interval;
515 // Estimate for general maximum lag as determined by server.
516 // Can raise to high values like 15s with eg. map generation mods.
517 float m_max_lag_estimate;
519 // peer_ids in here should be unique, except that there may be many 0s
520 std::vector<RemotePlayer*> m_players;
523 IntervalLimiter m_particle_management_interval;
524 UNORDERED_MAP<u32, float> m_particle_spawners;
525 UNORDERED_MAP<u32, u16> m_particle_spawner_attachments;
530 #include "clientobject.h"
531 #include "content_cao.h"
533 class ClientSimpleObject;
536 The client-side environment.
538 This is not thread-safe.
539 Must be called from main (irrlicht) thread (uses the SceneManager)
540 Client uses an environment mutex.
543 enum ClientEnvEventType
550 struct ClientEnvEvent
552 ClientEnvEventType type;
566 class ClientEnvironment : public Environment
569 ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
570 ITextureSource *texturesource, IGameDef *gamedef,
571 IrrlichtDevice *device);
572 ~ClientEnvironment();
575 ClientMap & getClientMap();
577 IGameDef *getGameDef()
578 { return m_gamedef; }
580 void step(f32 dtime);
582 virtual void setLocalPlayer(LocalPlayer *player);
583 LocalPlayer *getLocalPlayer() { return m_local_player; }
589 void addSimpleObject(ClientSimpleObject *simple);
595 GenericCAO* getGenericCAO(u16 id);
596 ClientActiveObject* getActiveObject(u16 id);
599 Adds an active object to the environment.
600 Environment handles deletion of object.
601 Object may be deleted by environment immediately.
602 If id of object is 0, assigns a free id to it.
603 Returns the id of the object.
604 Returns 0 if not added and thus deleted.
606 u16 addActiveObject(ClientActiveObject *object);
608 void addActiveObject(u16 id, u8 type, const std::string &init_data);
609 void removeActiveObject(u16 id);
611 void processActiveObjectMessage(u16 id, const std::string &data);
614 Callbacks for activeobjects
617 void damageLocalPlayer(u8 damage, bool handle_hp=true);
618 void updateLocalPlayerBreath(u16 breath);
621 Client likes to call these
624 // Get all nearby objects
625 void getActiveObjects(v3f origin, f32 max_d,
626 std::vector<DistanceSortedActiveObject> &dest);
628 // Get event from queue. CEE_NONE is returned if queue is empty.
629 ClientEnvEvent getClientEvent();
632 * Gets closest object pointed by the shootline.
633 * Returns NULL if not found.
635 * \param[in] shootline_on_map the shootline for
636 * the test in world coordinates
637 * \param[out] intersection_point the first point where
638 * the shootline meets the object. Valid only if
639 * not NULL is returned.
640 * \param[out] intersection_normal the normal vector of
641 * the intersection, pointing outwards. Zero vector if
642 * the shootline starts in an active object.
643 * Valid only if not NULL is returned.
645 ClientActiveObject * getSelectedActiveObject(
646 const core::line3d<f32> &shootline_on_map,
647 v3f *intersection_point,
648 v3s16 *intersection_normal
652 * Performs a raycast on the world.
653 * Returns the first thing the shootline meets.
655 * @param[in] shootline the shootline, starting from
656 * the camera position. This also gives the maximal distance
658 * @param[in] liquids_pointable if false, liquids are ignored
659 * @param[in] look_for_object if false, objects are ignored
661 PointedThing getPointedThing(
662 core::line3d<f32> shootline,
663 bool liquids_pointable,
664 bool look_for_object);
666 u16 attachement_parent_ids[USHRT_MAX + 1];
668 const std::list<std::string> &getPlayerNames() { return m_player_names; }
669 void addPlayerName(const std::string &name) { m_player_names.push_back(name); }
670 void removePlayerName(const std::string &name) { m_player_names.remove(name); }
671 void updateCameraOffset(v3s16 camera_offset)
672 { m_camera_offset = camera_offset; }
673 v3s16 getCameraOffset() const { return m_camera_offset; }
676 LocalPlayer *m_local_player;
677 scene::ISceneManager *m_smgr;
678 ITextureSource *m_texturesource;
680 IrrlichtDevice *m_irr;
681 UNORDERED_MAP<u16, ClientActiveObject*> m_active_objects;
682 std::vector<ClientSimpleObject*> m_simple_objects;
683 std::queue<ClientEnvEvent> m_client_event_queue;
684 IntervalLimiter m_active_object_light_update_interval;
685 IntervalLimiter m_lava_hurt_interval;
686 IntervalLimiter m_drowning_interval;
687 IntervalLimiter m_breathing_interval;
688 std::list<std::string> m_player_names;
689 v3s16 m_camera_offset;