serverenvironment.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. /*
  157. The server-side environment.
  158. This is not thread-safe. Server uses an environment mutex.
  159. */
  160. typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap;
  161. class ServerEnvironment : public Environment
  162. {
  163. public:
  164. ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
  165. Server *server, const std::string &path_world);
  166. ~ServerEnvironment();
  167. Map & getMap();
  168. ServerMap & getServerMap();
  169. //TODO find way to remove this fct!
  170. ServerScripting* getScriptIface()
  171. { return m_script; }
  172. Server *getGameDef()
  173. { return m_server; }
  174. float getSendRecommendedInterval()
  175. { return m_recommended_send_interval; }
  176. void kickAllPlayers(AccessDeniedCode reason,
  177. const std::string &str_reason, bool reconnect);
  178. // Save players
  179. void saveLoadedPlayers(bool force = false);
  180. void savePlayer(RemotePlayer *player);
  181. PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
  182. bool is_singleplayer);
  183. void addPlayer(RemotePlayer *player);
  184. void removePlayer(RemotePlayer *player);
  185. bool removePlayerFromDatabase(const std::string &name);
  186. /*
  187. Save and load time of day and game timer
  188. */
  189. void saveMeta();
  190. void loadMeta();
  191. u32 addParticleSpawner(float exptime);
  192. u32 addParticleSpawner(float exptime, u16 attached_id);
  193. void deleteParticleSpawner(u32 id, bool remove_from_object = true);
  194. /*
  195. External ActiveObject interface
  196. -------------------------------------------
  197. */
  198. ServerActiveObject* getActiveObject(u16 id)
  199. {
  200. return m_ao_manager.getActiveObject(id);
  201. }
  202. /*
  203. Add an active object to the environment.
  204. Environment handles deletion of object.
  205. Object may be deleted by environment immediately.
  206. If id of object is 0, assigns a free id to it.
  207. Returns the id of the object.
  208. Returns 0 if not added and thus deleted.
  209. */
  210. u16 addActiveObject(ServerActiveObject *object);
  211. /*
  212. Add an active object as a static object to the corresponding
  213. MapBlock.
  214. Caller allocates memory, ServerEnvironment frees memory.
  215. Return value: true if succeeded, false if failed.
  216. (note: not used, pending removal from engine)
  217. */
  218. //bool addActiveObjectAsStatic(ServerActiveObject *object);
  219. /*
  220. Find out what new objects have been added to
  221. inside a radius around a position
  222. */
  223. void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
  224. s16 player_radius,
  225. std::set<u16> &current_objects,
  226. std::queue<u16> &added_objects);
  227. /*
  228. Find out what new objects have been removed from
  229. inside a radius around a position
  230. */
  231. void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
  232. s16 player_radius,
  233. std::set<u16> &current_objects,
  234. std::queue<u16> &removed_objects);
  235. /*
  236. Get the next message emitted by some active object.
  237. Returns a message with id=0 if no messages are available.
  238. */
  239. ActiveObjectMessage getActiveObjectMessage();
  240. virtual void getSelectedActiveObjects(
  241. const core::line3d<f32> &shootline_on_map,
  242. std::vector<PointedThing> &objects
  243. );
  244. /*
  245. Activate objects and dynamically modify for the dtime determined
  246. from timestamp and additional_dtime
  247. */
  248. void activateBlock(MapBlock *block, u32 additional_dtime=0);
  249. /*
  250. {Active,Loading}BlockModifiers
  251. -------------------------------------------
  252. */
  253. void addActiveBlockModifier(ActiveBlockModifier *abm);
  254. void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
  255. /*
  256. Other stuff
  257. -------------------------------------------
  258. */
  259. // Script-aware node setters
  260. bool setNode(v3s16 p, const MapNode &n);
  261. bool removeNode(v3s16 p);
  262. bool swapNode(v3s16 p, const MapNode &n);
  263. // Find all active objects inside a radius around a point
  264. void getObjectsInsideRadius(std::vector<u16> &objects, const v3f &pos, float radius)
  265. {
  266. return m_ao_manager.getObjectsInsideRadius(pos, radius, objects);
  267. }
  268. // Clear objects, loading and going through every MapBlock
  269. void clearObjects(ClearObjectsMode mode);
  270. // This makes stuff happen
  271. void step(f32 dtime);
  272. /*!
  273. * Returns false if the given line intersects with a
  274. * non-air node, true otherwise.
  275. * \param pos1 start of the line
  276. * \param pos2 end of the line
  277. * \param p output, position of the first non-air node
  278. * the line intersects
  279. */
  280. bool line_of_sight(v3f pos1, v3f pos2, v3s16 *p = NULL);
  281. u32 getGameTime() const { return m_game_time; }
  282. void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
  283. float getMaxLagEstimate() { return m_max_lag_estimate; }
  284. std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
  285. // Sets the static object status all the active objects in the specified block
  286. // This is only really needed for deleting blocks from the map
  287. void setStaticForActiveObjectsInBlock(v3s16 blockpos,
  288. bool static_exists, v3s16 static_block=v3s16(0,0,0));
  289. RemotePlayer *getPlayer(const session_t peer_id);
  290. RemotePlayer *getPlayer(const char* name);
  291. u32 getPlayerCount() const { return m_players.size(); }
  292. static bool migratePlayersDatabase(const GameParams &game_params,
  293. const Settings &cmd_args);
  294. AuthDatabase *getAuthDatabase() { return m_auth_database; }
  295. static bool migrateAuthDatabase(const GameParams &game_params,
  296. const Settings &cmd_args);
  297. private:
  298. /**
  299. * called if env_meta.txt doesn't exist (e.g. new world)
  300. */
  301. void loadDefaultMeta();
  302. static PlayerDatabase *openPlayerDatabase(const std::string &name,
  303. const std::string &savedir, const Settings &conf);
  304. static AuthDatabase *openAuthDatabase(const std::string &name,
  305. const std::string &savedir, const Settings &conf);
  306. /*
  307. Internal ActiveObject interface
  308. -------------------------------------------
  309. */
  310. /*
  311. Add an active object to the environment.
  312. Called by addActiveObject.
  313. Object may be deleted by environment immediately.
  314. If id of object is 0, assigns a free id to it.
  315. Returns the id of the object.
  316. Returns 0 if not added and thus deleted.
  317. */
  318. u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
  319. /*
  320. Remove all objects that satisfy (isGone() && m_known_by_count==0)
  321. */
  322. void removeRemovedObjects();
  323. /*
  324. Convert stored objects from block to active
  325. */
  326. void activateObjects(MapBlock *block, u32 dtime_s);
  327. /*
  328. Convert objects that are not in active blocks to static.
  329. If m_known_by_count != 0, active object is not deleted, but static
  330. data is still updated.
  331. If force_delete is set, active object is deleted nevertheless. It
  332. shall only be set so in the destructor of the environment.
  333. */
  334. void deactivateFarObjects(bool force_delete);
  335. /*
  336. A few helpers used by the three above methods
  337. */
  338. void deleteStaticFromBlock(
  339. ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
  340. bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
  341. ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
  342. /*
  343. Member variables
  344. */
  345. // The map
  346. ServerMap *m_map;
  347. // Lua state
  348. ServerScripting* m_script;
  349. // Server definition
  350. Server *m_server;
  351. // Active Object Manager
  352. server::ActiveObjectMgr m_ao_manager;
  353. // World path
  354. const std::string m_path_world;
  355. // Outgoing network message buffer for active objects
  356. std::queue<ActiveObjectMessage> m_active_object_messages;
  357. // Some timers
  358. float m_send_recommended_timer = 0.0f;
  359. IntervalLimiter m_object_management_interval;
  360. // List of active blocks
  361. ActiveBlockList m_active_blocks;
  362. IntervalLimiter m_active_blocks_management_interval;
  363. IntervalLimiter m_active_block_modifier_interval;
  364. IntervalLimiter m_active_blocks_nodemetadata_interval;
  365. // Time from the beginning of the game in seconds.
  366. // Incremented in step().
  367. u32 m_game_time = 0;
  368. // A helper variable for incrementing the latter
  369. float m_game_time_fraction_counter = 0.0f;
  370. // Time of last clearObjects call (game time).
  371. // When a mapblock older than this is loaded, its objects are cleared.
  372. u32 m_last_clear_objects_time = 0;
  373. // Active block modifiers
  374. std::vector<ABMWithState> m_abms;
  375. LBMManager m_lbm_mgr;
  376. // An interval for generally sending object positions and stuff
  377. float m_recommended_send_interval = 0.1f;
  378. // Estimate for general maximum lag as determined by server.
  379. // Can raise to high values like 15s with eg. map generation mods.
  380. float m_max_lag_estimate = 0.1f;
  381. // peer_ids in here should be unique, except that there may be many 0s
  382. std::vector<RemotePlayer*> m_players;
  383. PlayerDatabase *m_player_database = nullptr;
  384. AuthDatabase *m_auth_database = nullptr;
  385. // Pseudo random generator for shuffling, etc.
  386. std::mt19937 m_rgen;
  387. // Particles
  388. IntervalLimiter m_particle_management_interval;
  389. std::unordered_map<u32, float> m_particle_spawners;
  390. std::unordered_map<u32, u16> m_particle_spawner_attachments;
  391. };