serverenvironment.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include "activeobject.h"
  18. #include "environment.h"
  19. #include "mapnode.h"
  20. #include "settings.h"
  21. #include "server/activeobjectmgr.h"
  22. #include "util/numeric.h"
  23. #include <set>
  24. #include <random>
  25. class IGameDef;
  26. class ServerMap;
  27. struct GameParams;
  28. class MapBlock;
  29. class RemotePlayer;
  30. class PlayerDatabase;
  31. class AuthDatabase;
  32. class PlayerSAO;
  33. class ServerEnvironment;
  34. class ActiveBlockModifier;
  35. struct StaticObject;
  36. class ServerActiveObject;
  37. class Server;
  38. class ServerScripting;
  39. /*
  40. {Active, Loading} block modifier interface.
  41. These are fed into ServerEnvironment at initialization time;
  42. ServerEnvironment handles deleting them.
  43. */
  44. class ActiveBlockModifier
  45. {
  46. public:
  47. ActiveBlockModifier() = default;
  48. virtual ~ActiveBlockModifier() = default;
  49. // Set of contents to trigger on
  50. virtual const std::vector<std::string> &getTriggerContents() const = 0;
  51. // Set of required neighbors (trigger doesn't happen if none are found)
  52. // Empty = do not check neighbors
  53. virtual const std::vector<std::string> &getRequiredNeighbors() const = 0;
  54. // Trigger interval in seconds
  55. virtual float getTriggerInterval() = 0;
  56. // Random chance of (1 / return value), 0 is disallowed
  57. virtual u32 getTriggerChance() = 0;
  58. // Whether to modify chance to simulate time lost by an unnattended block
  59. virtual bool getSimpleCatchUp() = 0;
  60. // This is called usually at interval for 1/chance of the nodes
  61. virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
  62. virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
  63. u32 active_object_count, u32 active_object_count_wider){};
  64. };
  65. struct ABMWithState
  66. {
  67. ActiveBlockModifier *abm;
  68. float timer = 0.0f;
  69. ABMWithState(ActiveBlockModifier *abm_);
  70. };
  71. struct LoadingBlockModifierDef
  72. {
  73. // Set of contents to trigger on
  74. std::set<std::string> trigger_contents;
  75. std::string name;
  76. bool run_at_every_load = false;
  77. virtual ~LoadingBlockModifierDef() = default;
  78. virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
  79. };
  80. struct LBMContentMapping
  81. {
  82. typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
  83. lbm_map map;
  84. std::vector<LoadingBlockModifierDef *> lbm_list;
  85. // Needs to be separate method (not inside destructor),
  86. // because the LBMContentMapping may be copied and destructed
  87. // many times during operation in the lbm_lookup_map.
  88. void deleteContents();
  89. void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
  90. const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
  91. };
  92. class LBMManager
  93. {
  94. public:
  95. LBMManager() = default;
  96. ~LBMManager();
  97. // Don't call this after loadIntroductionTimes() ran.
  98. void addLBMDef(LoadingBlockModifierDef *lbm_def);
  99. void loadIntroductionTimes(const std::string &times,
  100. IGameDef *gamedef, u32 now);
  101. // Don't call this before loadIntroductionTimes() ran.
  102. std::string createIntroductionTimesString();
  103. // Don't call this before loadIntroductionTimes() ran.
  104. void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
  105. // Warning: do not make this std::unordered_map, order is relevant here
  106. typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
  107. private:
  108. // Once we set this to true, we can only query,
  109. // not modify
  110. bool m_query_mode = false;
  111. // For m_query_mode == false:
  112. // The key of the map is the LBM def's name.
  113. // TODO make this std::unordered_map
  114. std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
  115. // For m_query_mode == true:
  116. // The key of the map is the LBM def's first introduction time.
  117. lbm_lookup_map m_lbm_lookup;
  118. // Returns an iterator to the LBMs that were introduced
  119. // after the given time. This is guaranteed to return
  120. // valid values for everything
  121. lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
  122. { return m_lbm_lookup.lower_bound(time); }
  123. };
  124. /*
  125. List of active blocks, used by ServerEnvironment
  126. */
  127. class ActiveBlockList
  128. {
  129. public:
  130. void update(std::vector<PlayerSAO*> &active_players,
  131. s16 active_block_range,
  132. s16 active_object_range,
  133. std::set<v3s16> &blocks_removed,
  134. std::set<v3s16> &blocks_added);
  135. bool contains(v3s16 p){
  136. return (m_list.find(p) != m_list.end());
  137. }
  138. void clear(){
  139. m_list.clear();
  140. }
  141. std::set<v3s16> m_list;
  142. std::set<v3s16> m_abm_list;
  143. std::set<v3s16> m_forceloaded_list;
  144. private:
  145. };
  146. /*
  147. Operation mode for ServerEnvironment::clearObjects()
  148. */
  149. enum ClearObjectsMode {
  150. // Load and go through every mapblock, clearing objects
  151. CLEAR_OBJECTS_MODE_FULL,
  152. // Clear objects immediately in loaded mapblocks;
  153. // clear objects in unloaded mapblocks only when the mapblocks are next activated.
  154. CLEAR_OBJECTS_MODE_QUICK,
  155. };
  156. class ServerEnvironment : public Environment
  157. {
  158. public:
  159. ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
  160. Server *server, const std::string &path_world);
  161. ~ServerEnvironment();
  162. Map & getMap();
  163. ServerMap & getServerMap();
  164. //TODO find way to remove this fct!
  165. ServerScripting* getScriptIface()
  166. { return m_script; }
  167. Server *getGameDef()
  168. { return m_server; }
  169. float getSendRecommendedInterval()
  170. { return m_recommended_send_interval; }
  171. void kickAllPlayers(AccessDeniedCode reason,
  172. const std::string &str_reason, bool reconnect);
  173. // Save players
  174. void saveLoadedPlayers(bool force = false);
  175. void savePlayer(RemotePlayer *player);
  176. PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
  177. bool is_singleplayer);
  178. void addPlayer(RemotePlayer *player);
  179. void removePlayer(RemotePlayer *player);
  180. bool removePlayerFromDatabase(const std::string &name);
  181. /*
  182. Save and load time of day and game timer
  183. */
  184. void saveMeta();
  185. void loadMeta();
  186. u32 addParticleSpawner(float exptime);
  187. u32 addParticleSpawner(float exptime, u16 attached_id);
  188. void deleteParticleSpawner(u32 id, bool remove_from_object = true);
  189. /*
  190. External ActiveObject interface
  191. -------------------------------------------
  192. */
  193. ServerActiveObject* getActiveObject(u16 id)
  194. {
  195. return m_ao_manager.getActiveObject(id);
  196. }
  197. /*
  198. Add an active object to the environment.
  199. Environment handles deletion of object.
  200. Object may be deleted by environment immediately.
  201. If id of object is 0, assigns a free id to it.
  202. Returns the id of the object.
  203. Returns 0 if not added and thus deleted.
  204. */
  205. u16 addActiveObject(ServerActiveObject *object);
  206. /*
  207. Add an active object as a static object to the corresponding
  208. MapBlock.
  209. Caller allocates memory, ServerEnvironment frees memory.
  210. Return value: true if succeeded, false if failed.
  211. (note: not used, pending removal from engine)
  212. */
  213. //bool addActiveObjectAsStatic(ServerActiveObject *object);
  214. /*
  215. Find out what new objects have been added to
  216. inside a radius around a position
  217. */
  218. void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
  219. s16 player_radius,
  220. std::set<u16> &current_objects,
  221. std::queue<u16> &added_objects);
  222. /*
  223. Find out what new objects have been removed from
  224. inside a radius around a position
  225. */
  226. void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
  227. s16 player_radius,
  228. std::set<u16> &current_objects,
  229. std::queue<u16> &removed_objects);
  230. /*
  231. Get the next message emitted by some active object.
  232. Returns false if no messages are available, true otherwise.
  233. */
  234. bool getActiveObjectMessage(ActiveObjectMessage *dest);
  235. virtual void getSelectedActiveObjects(
  236. const core::line3d<f32> &shootline_on_map,
  237. std::vector<PointedThing> &objects
  238. );
  239. /*
  240. Activate objects and dynamically modify for the dtime determined
  241. from timestamp and additional_dtime
  242. */
  243. void activateBlock(MapBlock *block, u32 additional_dtime=0);
  244. /*
  245. {Active,Loading}BlockModifiers
  246. -------------------------------------------
  247. */
  248. void addActiveBlockModifier(ActiveBlockModifier *abm);
  249. void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
  250. /*
  251. Other stuff
  252. -------------------------------------------
  253. */
  254. // Script-aware node setters
  255. bool setNode(v3s16 p, const MapNode &n);
  256. bool removeNode(v3s16 p);
  257. bool swapNode(v3s16 p, const MapNode &n);
  258. // Find the daylight value at pos with a Depth First Search
  259. u8 findSunlight(v3s16 pos) const;
  260. // Find all active objects inside a radius around a point
  261. void getObjectsInsideRadius(std::vector<ServerActiveObject *> &objects, const v3f &pos, float radius,
  262. std::function<bool(ServerActiveObject *obj)> include_obj_cb)
  263. {
  264. return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb);
  265. }
  266. // Find all active objects inside a box
  267. void getObjectsInArea(std::vector<ServerActiveObject *> &objects, const aabb3f &box,
  268. std::function<bool(ServerActiveObject *obj)> include_obj_cb)
  269. {
  270. return m_ao_manager.getObjectsInArea(box, objects, include_obj_cb);
  271. }
  272. // Clear objects, loading and going through every MapBlock
  273. void clearObjects(ClearObjectsMode mode);
  274. // This makes stuff happen
  275. void step(f32 dtime);
  276. u32 getGameTime() const { return m_game_time; }
  277. void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
  278. float getMaxLagEstimate() { return m_max_lag_estimate; }
  279. std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
  280. // Sets the static object status all the active objects in the specified block
  281. // This is only really needed for deleting blocks from the map
  282. void setStaticForActiveObjectsInBlock(v3s16 blockpos,
  283. bool static_exists, v3s16 static_block=v3s16(0,0,0));
  284. RemotePlayer *getPlayer(const session_t peer_id);
  285. RemotePlayer *getPlayer(const char* name);
  286. const std::vector<RemotePlayer *> getPlayers() const { return m_players; }
  287. u32 getPlayerCount() const { return m_players.size(); }
  288. static bool migratePlayersDatabase(const GameParams &game_params,
  289. const Settings &cmd_args);
  290. AuthDatabase *getAuthDatabase() { return m_auth_database; }
  291. static bool migrateAuthDatabase(const GameParams &game_params,
  292. const Settings &cmd_args);
  293. private:
  294. /**
  295. * called if env_meta.txt doesn't exist (e.g. new world)
  296. */
  297. void loadDefaultMeta();
  298. static PlayerDatabase *openPlayerDatabase(const std::string &name,
  299. const std::string &savedir, const Settings &conf);
  300. static AuthDatabase *openAuthDatabase(const std::string &name,
  301. const std::string &savedir, const Settings &conf);
  302. /*
  303. Internal ActiveObject interface
  304. -------------------------------------------
  305. */
  306. /*
  307. Add an active object to the environment.
  308. Called by addActiveObject.
  309. Object may be deleted by environment immediately.
  310. If id of object is 0, assigns a free id to it.
  311. Returns the id of the object.
  312. Returns 0 if not added and thus deleted.
  313. */
  314. u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
  315. /*
  316. Remove all objects that satisfy (isGone() && m_known_by_count==0)
  317. */
  318. void removeRemovedObjects();
  319. /*
  320. Convert stored objects from block to active
  321. */
  322. void activateObjects(MapBlock *block, u32 dtime_s);
  323. /*
  324. Convert objects that are not in active blocks to static.
  325. If m_known_by_count != 0, active object is not deleted, but static
  326. data is still updated.
  327. If force_delete is set, active object is deleted nevertheless. It
  328. shall only be set so in the destructor of the environment.
  329. */
  330. void deactivateFarObjects(bool force_delete);
  331. /*
  332. A few helpers used by the three above methods
  333. */
  334. void deleteStaticFromBlock(
  335. ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
  336. bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
  337. ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
  338. /*
  339. Member variables
  340. */
  341. // The map
  342. ServerMap *m_map;
  343. // Lua state
  344. ServerScripting* m_script;
  345. // Server definition
  346. Server *m_server;
  347. // Active Object Manager
  348. server::ActiveObjectMgr m_ao_manager;
  349. // World path
  350. const std::string m_path_world;
  351. // Outgoing network message buffer for active objects
  352. std::queue<ActiveObjectMessage> m_active_object_messages;
  353. // Some timers
  354. float m_send_recommended_timer = 0.0f;
  355. IntervalLimiter m_object_management_interval;
  356. // List of active blocks
  357. ActiveBlockList m_active_blocks;
  358. IntervalLimiter m_active_blocks_management_interval;
  359. IntervalLimiter m_active_block_modifier_interval;
  360. IntervalLimiter m_active_blocks_nodemetadata_interval;
  361. // Whether the variables below have been read from file yet
  362. bool m_meta_loaded = false;
  363. // Time from the beginning of the game in seconds.
  364. // Incremented in step().
  365. u32 m_game_time = 0;
  366. // A helper variable for incrementing the latter
  367. float m_game_time_fraction_counter = 0.0f;
  368. // Time of last clearObjects call (game time).
  369. // When a mapblock older than this is loaded, its objects are cleared.
  370. u32 m_last_clear_objects_time = 0;
  371. // Active block modifiers
  372. std::vector<ABMWithState> m_abms;
  373. LBMManager m_lbm_mgr;
  374. // An interval for generally sending object positions and stuff
  375. float m_recommended_send_interval = 0.1f;
  376. // Estimate for general maximum lag as determined by server.
  377. // Can raise to high values like 15s with eg. map generation mods.
  378. float m_max_lag_estimate = 0.1f;
  379. // peer_ids in here should be unique, except that there may be many 0s
  380. std::vector<RemotePlayer*> m_players;
  381. PlayerDatabase *m_player_database = nullptr;
  382. AuthDatabase *m_auth_database = nullptr;
  383. // Pseudo random generator for shuffling, etc.
  384. std::mt19937 m_rgen;
  385. // Particles
  386. IntervalLimiter m_particle_management_interval;
  387. std::unordered_map<u32, float> m_particle_spawners;
  388. std::unordered_map<u32, u16> m_particle_spawner_attachments;
  389. ServerActiveObject* createSAO(ActiveObjectType type, v3f pos, const std::string &data);
  390. };