serverenvironment.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. // Luanti
  2. // SPDX-License-Identifier: LGPL-2.1-or-later
  3. // Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. #pragma once
  5. #include <set>
  6. #include <utility>
  7. #include "activeobject.h"
  8. #include "environment.h"
  9. #include "servermap.h"
  10. #include "settings.h"
  11. #include "server/activeobjectmgr.h"
  12. #include "util/numeric.h"
  13. #include "util/metricsbackend.h"
  14. class IGameDef;
  15. struct GameParams;
  16. class RemotePlayer;
  17. class PlayerDatabase;
  18. class AuthDatabase;
  19. class PlayerSAO;
  20. class ServerEnvironment;
  21. class ActiveBlockModifier;
  22. struct StaticObject;
  23. class ServerActiveObject;
  24. class Server;
  25. class ServerScripting;
  26. enum AccessDeniedCode : u8;
  27. typedef u16 session_t;
  28. /*
  29. {Active, Loading} block modifier interface.
  30. These are fed into ServerEnvironment at initialization time;
  31. ServerEnvironment handles deleting them.
  32. */
  33. class ActiveBlockModifier
  34. {
  35. public:
  36. ActiveBlockModifier() = default;
  37. virtual ~ActiveBlockModifier() = default;
  38. // Set of contents to trigger on
  39. virtual const std::vector<std::string> &getTriggerContents() const = 0;
  40. // Set of required neighbors (trigger doesn't happen if none are found)
  41. // Empty = do not check neighbors
  42. virtual const std::vector<std::string> &getRequiredNeighbors() const = 0;
  43. // Set of without neighbors (trigger doesn't happen if any are found)
  44. // Empty = do not check neighbors
  45. virtual const std::vector<std::string> &getWithoutNeighbors() const = 0;
  46. // Trigger interval in seconds
  47. virtual float getTriggerInterval() = 0;
  48. // Random chance of (1 / return value), 0 is disallowed
  49. virtual u32 getTriggerChance() = 0;
  50. // Whether to modify chance to simulate time lost by an unnattended block
  51. virtual bool getSimpleCatchUp() = 0;
  52. // get min Y for apply abm
  53. virtual s16 getMinY() = 0;
  54. // get max Y for apply abm
  55. virtual s16 getMaxY() = 0;
  56. // This is called usually at interval for 1/chance of the nodes
  57. virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
  58. virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
  59. u32 active_object_count, u32 active_object_count_wider){};
  60. };
  61. struct ABMWithState
  62. {
  63. ActiveBlockModifier *abm;
  64. float timer = 0.0f;
  65. ABMWithState(ActiveBlockModifier *abm_);
  66. };
  67. struct LoadingBlockModifierDef
  68. {
  69. // Set of contents to trigger on
  70. std::vector<std::string> trigger_contents;
  71. std::string name;
  72. bool run_at_every_load = false;
  73. virtual ~LoadingBlockModifierDef() = default;
  74. /// @brief Called to invoke LBM
  75. /// @param env environment
  76. /// @param block the block in question
  77. /// @param positions set of node positions (block-relative!)
  78. /// @param dtime_s game time since last deactivation
  79. virtual void trigger(ServerEnvironment *env, MapBlock *block,
  80. const std::unordered_set<v3s16> &positions, float dtime_s) {};
  81. };
  82. class LBMContentMapping
  83. {
  84. public:
  85. typedef std::vector<LoadingBlockModifierDef*> lbm_vector;
  86. typedef std::unordered_map<content_t, lbm_vector> lbm_map;
  87. LBMContentMapping() = default;
  88. void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
  89. const lbm_map::mapped_type *lookup(content_t c) const;
  90. const lbm_vector &getList() const { return lbm_list; }
  91. // This struct owns the LBM pointers.
  92. ~LBMContentMapping();
  93. DISABLE_CLASS_COPY(LBMContentMapping);
  94. ALLOW_CLASS_MOVE(LBMContentMapping);
  95. private:
  96. lbm_vector lbm_list;
  97. lbm_map map;
  98. };
  99. class LBMManager
  100. {
  101. public:
  102. LBMManager() = default;
  103. ~LBMManager();
  104. // Don't call this after loadIntroductionTimes() ran.
  105. void addLBMDef(LoadingBlockModifierDef *lbm_def);
  106. void loadIntroductionTimes(const std::string &times,
  107. IGameDef *gamedef, u32 now);
  108. // Don't call this before loadIntroductionTimes() ran.
  109. std::string createIntroductionTimesString();
  110. // Don't call this before loadIntroductionTimes() ran.
  111. void applyLBMs(ServerEnvironment *env, MapBlock *block,
  112. u32 stamp, float dtime_s);
  113. // Warning: do not make this std::unordered_map, order is relevant here
  114. typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
  115. private:
  116. // Once we set this to true, we can only query,
  117. // not modify
  118. bool m_query_mode = false;
  119. // For m_query_mode == false:
  120. // The key of the map is the LBM def's name.
  121. std::unordered_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(std::unique_ptr<ServerMap> map, Server *server, MetricsBackend *mb);
  183. ~ServerEnvironment();
  184. void init();
  185. Map & getMap();
  186. ServerMap & getServerMap();
  187. //TODO find way to remove this fct!
  188. ServerScripting* getScriptIface()
  189. { return m_script; }
  190. Server *getGameDef()
  191. { return m_server; }
  192. float getSendRecommendedInterval()
  193. { return m_recommended_send_interval; }
  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(std::unique_ptr<ServerActiveObject> object);
  227. void invalidateActiveObjectObserverCaches();
  228. /*
  229. Find out what new objects have been added to
  230. inside a radius around a position
  231. */
  232. void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
  233. s16 player_radius,
  234. const std::set<u16> &current_objects,
  235. std::vector<u16> &added_objects);
  236. /*
  237. Find out what new objects have been removed from
  238. inside a radius around a position
  239. */
  240. void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
  241. s16 player_radius,
  242. const std::set<u16> &current_objects,
  243. std::vector<std::pair<bool /* gone? */, u16>> &removed_objects);
  244. /*
  245. Get the next message emitted by some active object.
  246. Returns false if no messages are available, true otherwise.
  247. */
  248. bool getActiveObjectMessage(ActiveObjectMessage *dest);
  249. virtual void getSelectedActiveObjects(
  250. const core::line3d<f32> &shootline_on_map,
  251. std::vector<PointedThing> &objects,
  252. const std::optional<Pointabilities> &pointabilities
  253. );
  254. /*
  255. Activate objects and dynamically modify for the dtime determined
  256. from timestamp and additional_dtime
  257. */
  258. void activateBlock(MapBlock *block, u32 additional_dtime=0);
  259. /*
  260. {Active,Loading}BlockModifiers
  261. -------------------------------------------
  262. */
  263. void addActiveBlockModifier(ActiveBlockModifier *abm);
  264. void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
  265. /*
  266. Other stuff
  267. -------------------------------------------
  268. */
  269. // Script-aware node setters
  270. bool setNode(v3s16 p, const MapNode &n);
  271. bool removeNode(v3s16 p);
  272. bool swapNode(v3s16 p, const MapNode &n);
  273. // Find the daylight value at pos with a Depth First Search
  274. u8 findSunlight(v3s16 pos) const;
  275. // Find all active objects inside a radius around a point
  276. void getObjectsInsideRadius(std::vector<ServerActiveObject *> &objects, const v3f &pos, float radius,
  277. std::function<bool(ServerActiveObject *obj)> include_obj_cb)
  278. {
  279. return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb);
  280. }
  281. // Find all active objects inside a box
  282. void getObjectsInArea(std::vector<ServerActiveObject *> &objects, const aabb3f &box,
  283. std::function<bool(ServerActiveObject *obj)> include_obj_cb)
  284. {
  285. return m_ao_manager.getObjectsInArea(box, objects, include_obj_cb);
  286. }
  287. // Clear objects, loading and going through every MapBlock
  288. void clearObjects(ClearObjectsMode mode);
  289. // to be called before destructor
  290. void deactivateBlocksAndObjects();
  291. // This makes stuff happen
  292. void step(f32 dtime);
  293. u32 getGameTime() const { return m_game_time; }
  294. void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
  295. float getMaxLagEstimate() const { return m_max_lag_estimate; }
  296. std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; }
  297. // Sorted by how ready a mapblock is
  298. enum BlockStatus {
  299. BS_UNKNOWN,
  300. BS_EMERGING,
  301. BS_LOADED,
  302. BS_ACTIVE // always highest value
  303. };
  304. BlockStatus getBlockStatus(v3s16 blockpos);
  305. // Sets the static object status all the active objects in the specified block
  306. // This is only really needed for deleting blocks from the map
  307. void setStaticForActiveObjectsInBlock(v3s16 blockpos,
  308. bool static_exists, v3s16 static_block=v3s16(0,0,0));
  309. RemotePlayer *getPlayer(const session_t peer_id);
  310. RemotePlayer *getPlayer(const std::string &name, bool match_invalid_peer = false);
  311. const std::vector<RemotePlayer *> getPlayers() const { return m_players; }
  312. u32 getPlayerCount() const { return m_players.size(); }
  313. static bool migratePlayersDatabase(const GameParams &game_params,
  314. const Settings &cmd_args);
  315. AuthDatabase *getAuthDatabase() { return m_auth_database; }
  316. static bool migrateAuthDatabase(const GameParams &game_params,
  317. const Settings &cmd_args);
  318. private:
  319. /**
  320. * called if env_meta.txt doesn't exist (e.g. new world)
  321. */
  322. void loadDefaultMeta();
  323. static PlayerDatabase *openPlayerDatabase(const std::string &name,
  324. const std::string &savedir, const Settings &conf);
  325. static AuthDatabase *openAuthDatabase(const std::string &name,
  326. const std::string &savedir, const Settings &conf);
  327. /*
  328. Internal ActiveObject interface
  329. -------------------------------------------
  330. */
  331. /*
  332. Add an active object to the environment.
  333. Called by addActiveObject.
  334. Object may be deleted by environment immediately.
  335. If id of object is 0, assigns a free id to it.
  336. Returns the id of the object.
  337. Returns 0 if not added and thus deleted.
  338. */
  339. u16 addActiveObjectRaw(std::unique_ptr<ServerActiveObject> object,
  340. const StaticObject *from_static, u32 dtime_s);
  341. /*
  342. Remove all objects that satisfy (isGone() && m_known_by_count==0)
  343. */
  344. void removeRemovedObjects();
  345. /*
  346. Convert stored objects from block to active
  347. */
  348. void activateObjects(MapBlock *block, u32 dtime_s);
  349. /*
  350. Convert objects that are not in active blocks to static.
  351. If m_known_by_count != 0, active object is not deleted, but static
  352. data is still updated.
  353. If force_delete is set, active object is deleted nevertheless. It
  354. shall only be set so in the destructor of the environment.
  355. */
  356. void deactivateFarObjects(bool force_delete);
  357. /*
  358. A few helpers used by the three above methods
  359. */
  360. void deleteStaticFromBlock(
  361. ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
  362. bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
  363. ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
  364. void processActiveObjectRemove(ServerActiveObject *obj);
  365. /*
  366. Member variables
  367. */
  368. // The map
  369. std::unique_ptr<ServerMap> m_map;
  370. // Lua state
  371. ServerScripting* m_script;
  372. // Server definition
  373. Server *m_server;
  374. // Active Object Manager
  375. server::ActiveObjectMgr m_ao_manager;
  376. // on_mapblocks_changed map event receiver
  377. OnMapblocksChangedReceiver m_on_mapblocks_changed_receiver;
  378. // Outgoing network message buffer for active objects
  379. std::queue<ActiveObjectMessage> m_active_object_messages;
  380. // Some timers
  381. float m_send_recommended_timer = 0.0f;
  382. IntervalLimiter m_object_management_interval;
  383. // List of active blocks
  384. ActiveBlockList m_active_blocks;
  385. int m_fast_active_block_divider = 1;
  386. IntervalLimiter m_active_blocks_mgmt_interval;
  387. IntervalLimiter m_active_block_modifier_interval;
  388. IntervalLimiter m_active_blocks_nodemetadata_interval;
  389. // Whether the variables below have been read from file yet
  390. bool m_meta_loaded = false;
  391. // Time from the beginning of the game in seconds.
  392. // Incremented in step().
  393. u32 m_game_time = 0;
  394. // A helper variable for incrementing the latter
  395. float m_game_time_fraction_counter = 0.0f;
  396. // Time of last clearObjects call (game time).
  397. // When a mapblock older than this is loaded, its objects are cleared.
  398. u32 m_last_clear_objects_time = 0;
  399. // Active block modifiers
  400. std::vector<ABMWithState> m_abms;
  401. LBMManager m_lbm_mgr;
  402. // An interval for generally sending object positions and stuff
  403. float m_recommended_send_interval = 0.1f;
  404. // Estimate for general maximum lag as determined by server.
  405. // Can raise to high values like 15s with eg. map generation mods.
  406. float m_max_lag_estimate = 0.1f;
  407. // peer_ids in here should be unique, except that there may be many 0s
  408. std::vector<RemotePlayer*> m_players;
  409. PlayerDatabase *m_player_database = nullptr;
  410. AuthDatabase *m_auth_database = nullptr;
  411. // Particles
  412. IntervalLimiter m_particle_management_interval;
  413. std::unordered_map<u32, float> m_particle_spawners;
  414. u32 m_particle_spawners_id_last_used = 0;
  415. std::unordered_map<u32, u16> m_particle_spawner_attachments;
  416. // Environment metrics
  417. MetricCounterPtr m_step_time_counter;
  418. MetricGaugePtr m_active_block_gauge;
  419. MetricGaugePtr m_active_object_gauge;
  420. std::unique_ptr<ServerActiveObject> createSAO(ActiveObjectType type, v3f pos,
  421. const std::string &data);
  422. };