serverenvironment.h 15 KB

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