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);
78 u32 getDayNightRatio();
81 virtual void setTimeOfDay(u32 time);
83 float getTimeOfDayF();
85 void stepTimeOfDay(float dtime);
87 void setTimeOfDaySpeed(float speed);
89 void setDayNightRatioOverride(bool enable, u32 value);
93 // counter used internally when triggering ABMs
97 Player * getPlayer(u16 peer_id);
98 Player * getPlayer(const char *name);
100 // peer_ids in here should be unique, except that there may be many 0s
101 std::vector<Player*> m_players;
103 GenericAtomic<float> m_time_of_day_speed;
106 * Below: values managed by m_time_lock
108 // Time of day in milli-hours (0-23999); determines day and night
110 // Time of day in 0...1
111 float m_time_of_day_f;
112 // Stores the skew created by the float -> u32 conversion
113 // to be applied at next conversion, so that there is no real skew.
114 float m_time_conversion_skew;
115 // Overriding the day-night ratio is useful for custom sky visuals
116 bool m_enable_day_night_ratio_override;
117 u32 m_day_night_ratio_override;
118 // Days from the server start, accounts for time shift
119 // in game (e.g. /time or bed usage)
120 Atomic<u32> m_day_count;
122 * Above: values managed by m_time_lock
125 /* TODO: Add a callback function so these can be updated when a setting
126 * changes. At this point in time it doesn't matter (e.g. /set
127 * is documented to change server settings only)
129 * TODO: Local caching of settings is not optimal and should at some stage
130 * be updated to use a global settings object for getting thse values
131 * (as opposed to the this local caching). This can be addressed in
134 bool m_cache_enable_shaders;
135 float m_cache_active_block_mgmt_interval;
136 float m_cache_abm_interval;
137 float m_cache_nodetimer_interval;
142 DISABLE_CLASS_COPY(Environment);
146 {Active, Loading} block modifier interface.
148 These are fed into ServerEnvironment at initialization time;
149 ServerEnvironment handles deleting them.
152 class ActiveBlockModifier
155 ActiveBlockModifier(){};
156 virtual ~ActiveBlockModifier(){};
158 // Set of contents to trigger on
159 virtual std::set<std::string> getTriggerContents()=0;
160 // Set of required neighbors (trigger doesn't happen if none are found)
161 // Empty = do not check neighbors
162 virtual std::set<std::string> getRequiredNeighbors()
163 { return std::set<std::string>(); }
164 // Trigger interval in seconds
165 virtual float getTriggerInterval() = 0;
166 // Random chance of (1 / return value), 0 is disallowed
167 virtual u32 getTriggerChance() = 0;
168 // Whether to modify chance to simulate time lost by an unnattended block
169 virtual bool getSimpleCatchUp() = 0;
170 // This is called usually at interval for 1/chance of the nodes
171 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
172 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
173 u32 active_object_count, u32 active_object_count_wider){};
178 ActiveBlockModifier *abm;
181 ABMWithState(ActiveBlockModifier *abm_);
184 struct LoadingBlockModifierDef
186 // Set of contents to trigger on
187 std::set<std::string> trigger_contents;
189 bool run_at_every_load;
191 virtual ~LoadingBlockModifierDef() {}
192 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
195 struct LBMContentMapping
197 typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
200 std::vector<LoadingBlockModifierDef *> lbm_list;
202 // Needs to be separate method (not inside destructor),
203 // because the LBMContentMapping may be copied and destructed
204 // many times during operation in the lbm_lookup_map.
205 void deleteContents();
206 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
207 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
219 // Don't call this after loadIntroductionTimes() ran.
220 void addLBMDef(LoadingBlockModifierDef *lbm_def);
222 void loadIntroductionTimes(const std::string ×,
223 IGameDef *gamedef, u32 now);
225 // Don't call this before loadIntroductionTimes() ran.
226 std::string createIntroductionTimesString();
228 // Don't call this before loadIntroductionTimes() ran.
229 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
231 // Warning: do not make this std::unordered_map, order is relevant here
232 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
235 // Once we set this to true, we can only query,
239 // For m_query_mode == false:
240 // The key of the map is the LBM def's name.
241 // TODO make this std::unordered_map
242 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
244 // For m_query_mode == true:
245 // The key of the map is the LBM def's first introduction time.
246 lbm_lookup_map m_lbm_lookup;
248 // Returns an iterator to the LBMs that were introduced
249 // after the given time. This is guaranteed to return
250 // valid values for everything
251 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
252 { return m_lbm_lookup.lower_bound(time); }
256 List of active blocks, used by ServerEnvironment
259 class ActiveBlockList
262 void update(std::vector<v3s16> &active_positions,
264 std::set<v3s16> &blocks_removed,
265 std::set<v3s16> &blocks_added);
267 bool contains(v3s16 p){
268 return (m_list.find(p) != m_list.end());
275 std::set<v3s16> m_list;
276 std::set<v3s16> m_forceloaded_list;
282 Operation mode for ServerEnvironment::clearObjects()
284 enum ClearObjectsMode {
285 // Load and go through every mapblock, clearing objects
286 CLEAR_OBJECTS_MODE_FULL,
288 // Clear objects immediately in loaded mapblocks;
289 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
290 CLEAR_OBJECTS_MODE_QUICK,
294 The server-side environment.
296 This is not thread-safe. Server uses an environment mutex.
299 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
301 class ServerEnvironment : public Environment
304 ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
305 IGameDef *gamedef, const std::string &path_world);
306 ~ServerEnvironment();
310 ServerMap & getServerMap();
312 //TODO find way to remove this fct!
313 GameScripting* getScriptIface()
316 IGameDef *getGameDef()
317 { return m_gamedef; }
319 float getSendRecommendedInterval()
320 { return m_recommended_send_interval; }
322 void kickAllPlayers(AccessDeniedCode reason,
323 const std::string &str_reason, bool reconnect);
325 void saveLoadedPlayers();
326 void savePlayer(RemotePlayer *player);
327 Player *loadPlayer(const std::string &playername);
330 Save and load time of day and game timer
334 // to be called instead of loadMeta if
335 // env_meta.txt doesn't exist (e.g. new world)
336 void loadDefaultMeta();
338 u32 addParticleSpawner(float exptime);
339 void deleteParticleSpawner(u32 id) { m_particle_spawners.erase(id); }
342 External ActiveObject interface
343 -------------------------------------------
346 ServerActiveObject* getActiveObject(u16 id);
349 Add an active object to the environment.
350 Environment handles deletion of object.
351 Object may be deleted by environment immediately.
352 If id of object is 0, assigns a free id to it.
353 Returns the id of the object.
354 Returns 0 if not added and thus deleted.
356 u16 addActiveObject(ServerActiveObject *object);
359 Add an active object as a static object to the corresponding
361 Caller allocates memory, ServerEnvironment frees memory.
362 Return value: true if succeeded, false if failed.
363 (note: not used, pending removal from engine)
365 //bool addActiveObjectAsStatic(ServerActiveObject *object);
368 Find out what new objects have been added to
369 inside a radius around a position
371 void getAddedActiveObjects(Player *player, s16 radius,
373 std::set<u16> ¤t_objects,
374 std::queue<u16> &added_objects);
377 Find out what new objects have been removed from
378 inside a radius around a position
380 void getRemovedActiveObjects(Player* player, s16 radius,
382 std::set<u16> ¤t_objects,
383 std::queue<u16> &removed_objects);
386 Get the next message emitted by some active object.
387 Returns a message with id=0 if no messages are available.
389 ActiveObjectMessage getActiveObjectMessage();
392 Activate objects and dynamically modify for the dtime determined
393 from timestamp and additional_dtime
395 void activateBlock(MapBlock *block, u32 additional_dtime=0);
398 {Active,Loading}BlockModifiers
399 -------------------------------------------
402 void addActiveBlockModifier(ActiveBlockModifier *abm);
403 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
407 -------------------------------------------
410 // Script-aware node setters
411 bool setNode(v3s16 p, const MapNode &n);
412 bool removeNode(v3s16 p);
413 bool swapNode(v3s16 p, const MapNode &n);
415 // Find all active objects inside a radius around a point
416 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
418 // Clear objects, loading and going through every MapBlock
419 void clearObjects(ClearObjectsMode mode);
421 // This makes stuff happen
422 void step(f32 dtime);
424 //check if there's a line of sight between two positions
425 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
427 u32 getGameTime() { return m_game_time; }
429 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
430 float getMaxLagEstimate() { return m_max_lag_estimate; }
432 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
434 // Sets the static object status all the active objects in the specified block
435 // This is only really needed for deleting blocks from the map
436 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
437 bool static_exists, v3s16 static_block=v3s16(0,0,0));
439 RemotePlayer *getPlayer(const u16 peer_id);
440 RemotePlayer *getPlayer(const char* name);
444 Internal ActiveObject interface
445 -------------------------------------------
449 Add an active object to the environment.
451 Called by addActiveObject.
453 Object may be deleted by environment immediately.
454 If id of object is 0, assigns a free id to it.
455 Returns the id of the object.
456 Returns 0 if not added and thus deleted.
458 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
461 Remove all objects that satisfy (m_removed && m_known_by_count==0)
463 void removeRemovedObjects();
466 Convert stored objects from block to active
468 void activateObjects(MapBlock *block, u32 dtime_s);
471 Convert objects that are not in active blocks to static.
473 If m_known_by_count != 0, active object is not deleted, but static
474 data is still updated.
476 If force_delete is set, active object is deleted nevertheless. It
477 shall only be set so in the destructor of the environment.
479 void deactivateFarObjects(bool force_delete);
488 GameScripting* m_script;
492 const std::string m_path_world;
493 // Active object list
494 ActiveObjectMap m_active_objects;
495 // Outgoing network message buffer for active objects
496 std::queue<ActiveObjectMessage> m_active_object_messages;
498 float m_send_recommended_timer;
499 IntervalLimiter m_object_management_interval;
500 // List of active blocks
501 ActiveBlockList m_active_blocks;
502 IntervalLimiter m_active_blocks_management_interval;
503 IntervalLimiter m_active_block_modifier_interval;
504 IntervalLimiter m_active_blocks_nodemetadata_interval;
505 int m_active_block_interval_overload_skip;
506 // Time from the beginning of the game in seconds.
507 // Incremented in step().
509 // A helper variable for incrementing the latter
510 float m_game_time_fraction_counter;
511 // Time of last clearObjects call (game time).
512 // When a mapblock older than this is loaded, its objects are cleared.
513 u32 m_last_clear_objects_time;
514 // Active block modifiers
515 std::vector<ABMWithState> m_abms;
516 LBMManager m_lbm_mgr;
517 // An interval for generally sending object positions and stuff
518 float m_recommended_send_interval;
519 // Estimate for general maximum lag as determined by server.
520 // Can raise to high values like 15s with eg. map generation mods.
521 float m_max_lag_estimate;
524 IntervalLimiter m_particle_management_interval;
525 UNORDERED_MAP<u32, float> m_particle_spawners;
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 addPlayer(Player *player);
583 LocalPlayer * getLocalPlayer();
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();
631 u16 attachement_parent_ids[USHRT_MAX + 1];
633 std::list<std::string> getPlayerNames()
634 { return m_player_names; }
635 void addPlayerName(std::string name)
636 { m_player_names.push_back(name); }
637 void removePlayerName(std::string name)
638 { m_player_names.remove(name); }
639 void updateCameraOffset(v3s16 camera_offset)
640 { m_camera_offset = camera_offset; }
641 v3s16 getCameraOffset() const { return m_camera_offset; }
643 LocalPlayer *getPlayer(const u16 peer_id);
644 LocalPlayer *getPlayer(const char* name);
648 scene::ISceneManager *m_smgr;
649 ITextureSource *m_texturesource;
651 IrrlichtDevice *m_irr;
652 std::map<u16, ClientActiveObject*> m_active_objects;
653 std::vector<ClientSimpleObject*> m_simple_objects;
654 std::queue<ClientEnvEvent> m_client_event_queue;
655 IntervalLimiter m_active_object_light_update_interval;
656 IntervalLimiter m_lava_hurt_interval;
657 IntervalLimiter m_drowning_interval;
658 IntervalLimiter m_breathing_interval;
659 std::list<std::string> m_player_names;
660 v3s16 m_camera_offset;