serverenvironment.h 15 KB

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