serverenvironment.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. 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 std::vector<LoadingBlockModifierDef *> *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. // TODO make this std::unordered_map
  121. std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
  122. // For m_query_mode == true:
  123. // The key of the map is the LBM def's first introduction time.
  124. lbm_lookup_map m_lbm_lookup;
  125. // Returns an iterator to the LBMs that were introduced
  126. // after the given time. This is guaranteed to return
  127. // valid values for everything
  128. lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
  129. { return m_lbm_lookup.lower_bound(time); }
  130. };
  131. /*
  132. List of active blocks, used by ServerEnvironment
  133. */
  134. class ActiveBlockList
  135. {
  136. public:
  137. void update(std::vector<PlayerSAO*> &active_players,
  138. s16 active_block_range,
  139. s16 active_object_range,
  140. std::set<v3s16> &blocks_removed,
  141. std::set<v3s16> &blocks_added,
  142. std::set<v3s16> &extra_blocks_added);
  143. bool contains(v3s16 p) const {
  144. return (m_list.find(p) != m_list.end());
  145. }
  146. auto size() const {
  147. return m_list.size();
  148. }
  149. void clear() {
  150. m_list.clear();
  151. }
  152. void remove(v3s16 p) {
  153. m_list.erase(p);
  154. m_abm_list.erase(p);
  155. }
  156. std::set<v3s16> m_list;
  157. std::set<v3s16> m_abm_list;
  158. // list of blocks that are always active, not modified by this class
  159. std::set<v3s16> m_forceloaded_list;
  160. };
  161. /*
  162. ServerEnvironment::m_on_mapblocks_changed_receiver
  163. */
  164. struct OnMapblocksChangedReceiver : public MapEventReceiver {
  165. std::unordered_set<v3s16> modified_blocks;
  166. bool receiving = false;
  167. void onMapEditEvent(const MapEditEvent &event) override;
  168. };
  169. /*
  170. Operation mode for ServerEnvironment::clearObjects()
  171. */
  172. enum ClearObjectsMode {
  173. // Load and go through every mapblock, clearing objects
  174. CLEAR_OBJECTS_MODE_FULL,
  175. // Clear objects immediately in loaded mapblocks;
  176. // clear objects in unloaded mapblocks only when the mapblocks are next activated.
  177. CLEAR_OBJECTS_MODE_QUICK,
  178. };
  179. class ServerEnvironment final : public Environment
  180. {
  181. public:
  182. ServerEnvironment(ServerMap *map, ServerScripting *script_iface,
  183. Server *server, const std::string &path_world, MetricsBackend *mb);
  184. ~ServerEnvironment();
  185. void init();
  186. Map & getMap();
  187. ServerMap & getServerMap();
  188. //TODO find way to remove this fct!
  189. ServerScripting* getScriptIface()
  190. { return m_script; }
  191. Server *getGameDef()
  192. { return m_server; }
  193. float getSendRecommendedInterval()
  194. { return m_recommended_send_interval; }
  195. // Save players
  196. void saveLoadedPlayers(bool force = false);
  197. void savePlayer(RemotePlayer *player);
  198. PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
  199. bool is_singleplayer);
  200. void addPlayer(RemotePlayer *player);
  201. void removePlayer(RemotePlayer *player);
  202. bool removePlayerFromDatabase(const std::string &name);
  203. /*
  204. Save and load time of day and game timer
  205. */
  206. void saveMeta();
  207. void loadMeta();
  208. u32 addParticleSpawner(float exptime);
  209. u32 addParticleSpawner(float exptime, u16 attached_id);
  210. void deleteParticleSpawner(u32 id, bool remove_from_object = true);
  211. /*
  212. External ActiveObject interface
  213. -------------------------------------------
  214. */
  215. ServerActiveObject* getActiveObject(u16 id)
  216. {
  217. return m_ao_manager.getActiveObject(id);
  218. }
  219. /*
  220. Add an active object to the environment.
  221. Environment handles deletion of object.
  222. Object may be deleted by environment immediately.
  223. If id of object is 0, assigns a free id to it.
  224. Returns the id of the object.
  225. Returns 0 if not added and thus deleted.
  226. */
  227. u16 addActiveObject(std::unique_ptr<ServerActiveObject> object);
  228. /*
  229. Add an active object as a static object to the corresponding
  230. MapBlock.
  231. Caller allocates memory, ServerEnvironment frees memory.
  232. Return value: true if succeeded, false if failed.
  233. (note: not used, pending removal from engine)
  234. */
  235. //bool addActiveObjectAsStatic(ServerActiveObject *object);
  236. /*
  237. Find out what new objects have been added to
  238. inside a radius around a position
  239. */
  240. void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
  241. s16 player_radius,
  242. std::set<u16> &current_objects,
  243. std::queue<u16> &added_objects);
  244. /*
  245. Find out what new objects have been removed from
  246. inside a radius around a position
  247. */
  248. void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
  249. s16 player_radius,
  250. std::set<u16> &current_objects,
  251. std::queue<u16> &removed_objects);
  252. /*
  253. Get the next message emitted by some active object.
  254. Returns false if no messages are available, true otherwise.
  255. */
  256. bool getActiveObjectMessage(ActiveObjectMessage *dest);
  257. virtual void getSelectedActiveObjects(
  258. const core::line3d<f32> &shootline_on_map,
  259. std::vector<PointedThing> &objects,
  260. const std::optional<Pointabilities> &pointabilities
  261. );
  262. /*
  263. Activate objects and dynamically modify for the dtime determined
  264. from timestamp and additional_dtime
  265. */
  266. void activateBlock(MapBlock *block, u32 additional_dtime=0);
  267. /*
  268. {Active,Loading}BlockModifiers
  269. -------------------------------------------
  270. */
  271. void addActiveBlockModifier(ActiveBlockModifier *abm);
  272. void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
  273. /*
  274. Other stuff
  275. -------------------------------------------
  276. */
  277. // Script-aware node setters
  278. bool setNode(v3s16 p, const MapNode &n);
  279. bool removeNode(v3s16 p);
  280. bool swapNode(v3s16 p, const MapNode &n);
  281. // Find the daylight value at pos with a Depth First Search
  282. u8 findSunlight(v3s16 pos) const;
  283. // Find all active objects inside a radius around a point
  284. void getObjectsInsideRadius(std::vector<ServerActiveObject *> &objects, const v3f &pos, float radius,
  285. std::function<bool(ServerActiveObject *obj)> include_obj_cb)
  286. {
  287. return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb);
  288. }
  289. // Find all active objects inside a box
  290. void getObjectsInArea(std::vector<ServerActiveObject *> &objects, const aabb3f &box,
  291. std::function<bool(ServerActiveObject *obj)> include_obj_cb)
  292. {
  293. return m_ao_manager.getObjectsInArea(box, objects, include_obj_cb);
  294. }
  295. // Clear objects, loading and going through every MapBlock
  296. void clearObjects(ClearObjectsMode mode);
  297. // This makes stuff happen
  298. void step(f32 dtime);
  299. u32 getGameTime() const { return m_game_time; }
  300. void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
  301. float getMaxLagEstimate() const { return m_max_lag_estimate; }
  302. std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; }
  303. // Sorted by how ready a mapblock is
  304. enum BlockStatus {
  305. BS_UNKNOWN,
  306. BS_EMERGING,
  307. BS_LOADED,
  308. BS_ACTIVE // always highest value
  309. };
  310. BlockStatus getBlockStatus(v3s16 blockpos);
  311. // Sets the static object status all the active objects in the specified block
  312. // This is only really needed for deleting blocks from the map
  313. void setStaticForActiveObjectsInBlock(v3s16 blockpos,
  314. bool static_exists, v3s16 static_block=v3s16(0,0,0));
  315. RemotePlayer *getPlayer(const session_t peer_id);
  316. RemotePlayer *getPlayer(const char* name);
  317. const std::vector<RemotePlayer *> getPlayers() const { return m_players; }
  318. u32 getPlayerCount() const { return m_players.size(); }
  319. static bool migratePlayersDatabase(const GameParams &game_params,
  320. const Settings &cmd_args);
  321. AuthDatabase *getAuthDatabase() { return m_auth_database; }
  322. static bool migrateAuthDatabase(const GameParams &game_params,
  323. const Settings &cmd_args);
  324. private:
  325. /**
  326. * called if env_meta.txt doesn't exist (e.g. new world)
  327. */
  328. void loadDefaultMeta();
  329. static PlayerDatabase *openPlayerDatabase(const std::string &name,
  330. const std::string &savedir, const Settings &conf);
  331. static AuthDatabase *openAuthDatabase(const std::string &name,
  332. const std::string &savedir, const Settings &conf);
  333. /*
  334. Internal ActiveObject interface
  335. -------------------------------------------
  336. */
  337. /*
  338. Add an active object to the environment.
  339. Called by addActiveObject.
  340. Object may be deleted by environment immediately.
  341. If id of object is 0, assigns a free id to it.
  342. Returns the id of the object.
  343. Returns 0 if not added and thus deleted.
  344. */
  345. u16 addActiveObjectRaw(std::unique_ptr<ServerActiveObject> object,
  346. bool set_changed, u32 dtime_s);
  347. /*
  348. Remove all objects that satisfy (isGone() && m_known_by_count==0)
  349. */
  350. void removeRemovedObjects();
  351. /*
  352. Convert stored objects from block to active
  353. */
  354. void activateObjects(MapBlock *block, u32 dtime_s);
  355. /*
  356. Convert objects that are not in active blocks to static.
  357. If m_known_by_count != 0, active object is not deleted, but static
  358. data is still updated.
  359. If force_delete is set, active object is deleted nevertheless. It
  360. shall only be set so in the destructor of the environment.
  361. */
  362. void deactivateFarObjects(bool force_delete);
  363. /*
  364. A few helpers used by the three above methods
  365. */
  366. void deleteStaticFromBlock(
  367. ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
  368. bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
  369. ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
  370. void processActiveObjectRemove(ServerActiveObject *obj, u16 id);
  371. /*
  372. Member variables
  373. */
  374. // The map
  375. ServerMap *m_map;
  376. // Lua state
  377. ServerScripting* m_script;
  378. // Server definition
  379. Server *m_server;
  380. // Active Object Manager
  381. server::ActiveObjectMgr m_ao_manager;
  382. // on_mapblocks_changed map event receiver
  383. OnMapblocksChangedReceiver m_on_mapblocks_changed_receiver;
  384. // World path
  385. const std::string m_path_world;
  386. // Outgoing network message buffer for active objects
  387. std::queue<ActiveObjectMessage> m_active_object_messages;
  388. // Some timers
  389. float m_send_recommended_timer = 0.0f;
  390. IntervalLimiter m_object_management_interval;
  391. // List of active blocks
  392. ActiveBlockList m_active_blocks;
  393. int m_fast_active_block_divider = 1;
  394. IntervalLimiter m_active_blocks_mgmt_interval;
  395. IntervalLimiter m_active_block_modifier_interval;
  396. IntervalLimiter m_active_blocks_nodemetadata_interval;
  397. // Whether the variables below have been read from file yet
  398. bool m_meta_loaded = false;
  399. // Time from the beginning of the game in seconds.
  400. // Incremented in step().
  401. u32 m_game_time = 0;
  402. // A helper variable for incrementing the latter
  403. float m_game_time_fraction_counter = 0.0f;
  404. // Time of last clearObjects call (game time).
  405. // When a mapblock older than this is loaded, its objects are cleared.
  406. u32 m_last_clear_objects_time = 0;
  407. // Active block modifiers
  408. std::vector<ABMWithState> m_abms;
  409. LBMManager m_lbm_mgr;
  410. // An interval for generally sending object positions and stuff
  411. float m_recommended_send_interval = 0.1f;
  412. // Estimate for general maximum lag as determined by server.
  413. // Can raise to high values like 15s with eg. map generation mods.
  414. float m_max_lag_estimate = 0.1f;
  415. // peer_ids in here should be unique, except that there may be many 0s
  416. std::vector<RemotePlayer*> m_players;
  417. PlayerDatabase *m_player_database = nullptr;
  418. AuthDatabase *m_auth_database = nullptr;
  419. // Pseudo random generator for shuffling, etc.
  420. std::mt19937 m_rgen;
  421. // Particles
  422. IntervalLimiter m_particle_management_interval;
  423. std::unordered_map<u32, float> m_particle_spawners;
  424. u32 m_particle_spawners_id_last_used = 0;
  425. std::unordered_map<u32, u16> m_particle_spawner_attachments;
  426. // Environment metrics
  427. MetricCounterPtr m_step_time_counter;
  428. MetricGaugePtr m_active_block_gauge;
  429. MetricGaugePtr m_active_object_gauge;
  430. std::unique_ptr<ServerActiveObject> createSAO(ActiveObjectType type, v3f pos,
  431. const std::string &data);
  432. };