map.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 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 <iostream>
  18. #include <sstream>
  19. #include <set>
  20. #include <map>
  21. #include <list>
  22. #include "irrlichttypes_bloated.h"
  23. #include "mapblock.h"
  24. #include "mapnode.h"
  25. #include "constants.h"
  26. #include "voxel.h"
  27. #include "modifiedstate.h"
  28. #include "util/container.h"
  29. #include "util/metricsbackend.h"
  30. #include "util/numeric.h"
  31. #include "nodetimer.h"
  32. #include "map_settings_manager.h"
  33. #include "debug.h"
  34. class Settings;
  35. class MapDatabase;
  36. class ClientMap;
  37. class MapSector;
  38. class ServerMapSector;
  39. class MapBlock;
  40. class NodeMetadata;
  41. class IGameDef;
  42. class IRollbackManager;
  43. class EmergeManager;
  44. class MetricsBackend;
  45. class ServerEnvironment;
  46. struct BlockMakeData;
  47. /*
  48. MapEditEvent
  49. */
  50. enum MapEditEventType{
  51. // Node added (changed from air or something else to something)
  52. MEET_ADDNODE,
  53. // Node removed (changed to air)
  54. MEET_REMOVENODE,
  55. // Node swapped (changed without metadata change)
  56. MEET_SWAPNODE,
  57. // Node metadata changed
  58. MEET_BLOCK_NODE_METADATA_CHANGED,
  59. // Anything else (modified_blocks are set unsent)
  60. MEET_OTHER
  61. };
  62. struct MapEditEvent
  63. {
  64. MapEditEventType type = MEET_OTHER;
  65. v3s16 p;
  66. MapNode n = CONTENT_AIR;
  67. std::set<v3s16> modified_blocks;
  68. bool is_private_change = false;
  69. MapEditEvent() = default;
  70. // Sets the event's position and marks the block as modified.
  71. void setPositionModified(v3s16 pos)
  72. {
  73. p = pos;
  74. modified_blocks.insert(getNodeBlockPos(pos));
  75. }
  76. VoxelArea getArea() const
  77. {
  78. switch(type){
  79. case MEET_ADDNODE:
  80. case MEET_REMOVENODE:
  81. case MEET_SWAPNODE:
  82. case MEET_BLOCK_NODE_METADATA_CHANGED:
  83. return VoxelArea(p);
  84. case MEET_OTHER:
  85. {
  86. VoxelArea a;
  87. for (v3s16 p : modified_blocks) {
  88. v3s16 np1 = p*MAP_BLOCKSIZE;
  89. v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
  90. a.addPoint(np1);
  91. a.addPoint(np2);
  92. }
  93. return a;
  94. }
  95. }
  96. return VoxelArea();
  97. }
  98. };
  99. class MapEventReceiver
  100. {
  101. public:
  102. // event shall be deleted by caller after the call.
  103. virtual void onMapEditEvent(const MapEditEvent &event) = 0;
  104. };
  105. class Map /*: public NodeContainer*/
  106. {
  107. public:
  108. Map(IGameDef *gamedef);
  109. virtual ~Map();
  110. DISABLE_CLASS_COPY(Map);
  111. /*
  112. Drop (client) or delete (server) the map.
  113. */
  114. virtual void drop()
  115. {
  116. delete this;
  117. }
  118. void addEventReceiver(MapEventReceiver *event_receiver);
  119. void removeEventReceiver(MapEventReceiver *event_receiver);
  120. // event shall be deleted by caller after the call.
  121. void dispatchEvent(const MapEditEvent &event);
  122. // On failure returns NULL
  123. MapSector * getSectorNoGenerateNoLock(v2s16 p2d);
  124. // Same as the above (there exists no lock anymore)
  125. MapSector * getSectorNoGenerate(v2s16 p2d);
  126. /*
  127. This is overloaded by ClientMap and ServerMap to allow
  128. their differing fetch methods.
  129. */
  130. virtual MapSector * emergeSector(v2s16 p){ return NULL; }
  131. // Returns InvalidPositionException if not found
  132. MapBlock * getBlockNoCreate(v3s16 p);
  133. // Returns NULL if not found
  134. MapBlock * getBlockNoCreateNoEx(v3s16 p);
  135. /* Server overrides */
  136. virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true)
  137. { return getBlockNoCreateNoEx(p); }
  138. inline const NodeDefManager * getNodeDefManager() { return m_nodedef; }
  139. bool isValidPosition(v3s16 p);
  140. // throws InvalidPositionException if not found
  141. void setNode(v3s16 p, MapNode n);
  142. // Returns a CONTENT_IGNORE node if not found
  143. // If is_valid_position is not NULL then this will be set to true if the
  144. // position is valid, otherwise false
  145. MapNode getNode(v3s16 p, bool *is_valid_position = NULL);
  146. /*
  147. These handle lighting but not faces.
  148. */
  149. virtual void addNodeAndUpdate(v3s16 p, MapNode n,
  150. std::map<v3s16, MapBlock*> &modified_blocks,
  151. bool remove_metadata = true);
  152. void removeNodeAndUpdate(v3s16 p,
  153. std::map<v3s16, MapBlock*> &modified_blocks);
  154. /*
  155. Wrappers for the latter ones.
  156. These emit events.
  157. Return true if succeeded, false if not.
  158. */
  159. bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
  160. bool removeNodeWithEvent(v3s16 p);
  161. // Call these before and after saving of many blocks
  162. virtual void beginSave() {}
  163. virtual void endSave() {}
  164. virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
  165. /*
  166. Return true unless the map definitely cannot save blocks.
  167. */
  168. virtual bool maySaveBlocks() { return true; }
  169. // Server implements these.
  170. // Client leaves them as no-op.
  171. virtual bool saveBlock(MapBlock *block) { return false; }
  172. virtual bool deleteBlock(v3s16 blockpos) { return false; }
  173. /*
  174. Updates usage timers and unloads unused blocks and sectors.
  175. Saves modified blocks before unloading if possible.
  176. */
  177. void timerUpdate(float dtime, float unload_timeout, s32 max_loaded_blocks,
  178. std::vector<v3s16> *unloaded_blocks=NULL);
  179. /*
  180. Unloads all blocks with a zero refCount().
  181. Saves modified blocks before unloading if possible.
  182. */
  183. void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
  184. // Deletes sectors and their blocks from memory
  185. // Takes cache into account
  186. // If deleted sector is in sector cache, clears cache
  187. void deleteSectors(std::vector<v2s16> &list);
  188. // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
  189. virtual void PrintInfo(std::ostream &out);
  190. /*
  191. Node metadata
  192. These are basically coordinate wrappers to MapBlock
  193. */
  194. std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
  195. NodeMetadata *getNodeMetadata(v3s16 p);
  196. /**
  197. * Sets metadata for a node.
  198. * This method sets the metadata for a given node.
  199. * On success, it returns @c true and the object pointed to
  200. * by @p meta is then managed by the system and should
  201. * not be deleted by the caller.
  202. *
  203. * In case of failure, the method returns @c false and the
  204. * caller is still responsible for deleting the object!
  205. *
  206. * @param p node coordinates
  207. * @param meta pointer to @c NodeMetadata object
  208. * @return @c true on success, false on failure
  209. */
  210. bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
  211. void removeNodeMetadata(v3s16 p);
  212. /*
  213. Node Timers
  214. These are basically coordinate wrappers to MapBlock
  215. */
  216. NodeTimer getNodeTimer(v3s16 p);
  217. void setNodeTimer(const NodeTimer &t);
  218. void removeNodeTimer(v3s16 p);
  219. /*
  220. Utilities
  221. */
  222. // Iterates through all nodes in the area in an unspecified order.
  223. // The given callback takes the position as its first argument and the node
  224. // as its second. If it returns false, forEachNodeInArea returns early.
  225. template<typename F>
  226. void forEachNodeInArea(v3s16 minp, v3s16 maxp, F func)
  227. {
  228. v3s16 bpmin = getNodeBlockPos(minp);
  229. v3s16 bpmax = getNodeBlockPos(maxp);
  230. for (s16 bz = bpmin.Z; bz <= bpmax.Z; bz++)
  231. for (s16 bx = bpmin.X; bx <= bpmax.X; bx++)
  232. for (s16 by = bpmin.Y; by <= bpmax.Y; by++) {
  233. // y is iterated innermost to make use of the sector cache.
  234. v3s16 bp(bx, by, bz);
  235. MapBlock *block = getBlockNoCreateNoEx(bp);
  236. v3s16 basep = bp * MAP_BLOCKSIZE;
  237. s16 minx_block = rangelim(minp.X - basep.X, 0, MAP_BLOCKSIZE - 1);
  238. s16 miny_block = rangelim(minp.Y - basep.Y, 0, MAP_BLOCKSIZE - 1);
  239. s16 minz_block = rangelim(minp.Z - basep.Z, 0, MAP_BLOCKSIZE - 1);
  240. s16 maxx_block = rangelim(maxp.X - basep.X, 0, MAP_BLOCKSIZE - 1);
  241. s16 maxy_block = rangelim(maxp.Y - basep.Y, 0, MAP_BLOCKSIZE - 1);
  242. s16 maxz_block = rangelim(maxp.Z - basep.Z, 0, MAP_BLOCKSIZE - 1);
  243. for (s16 z_block = minz_block; z_block <= maxz_block; z_block++)
  244. for (s16 y_block = miny_block; y_block <= maxy_block; y_block++)
  245. for (s16 x_block = minx_block; x_block <= maxx_block; x_block++) {
  246. v3s16 p = basep + v3s16(x_block, y_block, z_block);
  247. MapNode n = block ?
  248. block->getNodeNoCheck(x_block, y_block, z_block) :
  249. MapNode(CONTENT_IGNORE);
  250. if (!func(p, n))
  251. return;
  252. }
  253. }
  254. }
  255. bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
  256. protected:
  257. IGameDef *m_gamedef;
  258. std::set<MapEventReceiver*> m_event_receivers;
  259. std::unordered_map<v2s16, MapSector*> m_sectors;
  260. // Be sure to set this to NULL when the cached sector is deleted
  261. MapSector *m_sector_cache = nullptr;
  262. v2s16 m_sector_cache_p;
  263. // This stores the properties of the nodes on the map.
  264. const NodeDefManager *m_nodedef;
  265. // Can be implemented by child class
  266. virtual void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) {}
  267. bool determineAdditionalOcclusionCheck(const v3s16 &pos_camera,
  268. const core::aabbox3d<s16> &block_bounds, v3s16 &check);
  269. bool isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target,
  270. float step, float stepfac, float start_offset, float end_offset,
  271. u32 needed_count);
  272. };
  273. /*
  274. ServerMap
  275. This is the only map class that is able to generate map.
  276. */
  277. class ServerMap : public Map
  278. {
  279. public:
  280. /*
  281. savedir: directory to which map data should be saved
  282. */
  283. ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, MetricsBackend *mb);
  284. ~ServerMap();
  285. /*
  286. Get a sector from somewhere.
  287. - Check memory
  288. - Check disk (doesn't load blocks)
  289. - Create blank one
  290. */
  291. MapSector *createSector(v2s16 p);
  292. /*
  293. Blocks are generated by using these and makeBlock().
  294. */
  295. bool blockpos_over_mapgen_limit(v3s16 p);
  296. bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
  297. void finishBlockMake(BlockMakeData *data,
  298. std::map<v3s16, MapBlock*> *changed_blocks);
  299. /*
  300. Get a block from somewhere.
  301. - Memory
  302. - Create blank
  303. */
  304. MapBlock *createBlock(v3s16 p);
  305. /*
  306. Forcefully get a block from somewhere.
  307. - Memory
  308. - Load from disk
  309. - Create blank filled with CONTENT_IGNORE
  310. */
  311. MapBlock *emergeBlock(v3s16 p, bool create_blank=true) override;
  312. /*
  313. Try to get a block.
  314. If it does not exist in memory, add it to the emerge queue.
  315. - Memory
  316. - Emerge Queue (deferred disk or generate)
  317. */
  318. MapBlock *getBlockOrEmerge(v3s16 p3d);
  319. bool isBlockInQueue(v3s16 pos);
  320. void addNodeAndUpdate(v3s16 p, MapNode n,
  321. std::map<v3s16, MapBlock*> &modified_blocks,
  322. bool remove_metadata) override;
  323. /*
  324. Database functions
  325. */
  326. static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
  327. // Call these before and after saving of blocks
  328. void beginSave() override;
  329. void endSave() override;
  330. void save(ModifiedState save_level) override;
  331. void listAllLoadableBlocks(std::vector<v3s16> &dst);
  332. void listAllLoadedBlocks(std::vector<v3s16> &dst);
  333. MapgenParams *getMapgenParams();
  334. bool saveBlock(MapBlock *block) override;
  335. static bool saveBlock(MapBlock *block, MapDatabase *db, int compression_level = -1);
  336. MapBlock* loadBlock(v3s16 p);
  337. // Database version
  338. void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
  339. bool deleteBlock(v3s16 blockpos) override;
  340. void updateVManip(v3s16 pos);
  341. // For debug printing
  342. void PrintInfo(std::ostream &out) override;
  343. bool isSavingEnabled(){ return m_map_saving_enabled; }
  344. u64 getSeed();
  345. /*!
  346. * Fixes lighting in one map block.
  347. * May modify other blocks as well, as light can spread
  348. * out of the specified block.
  349. * Returns false if the block is not generated (so nothing
  350. * changed), true otherwise.
  351. */
  352. bool repairBlockLight(v3s16 blockpos,
  353. std::map<v3s16, MapBlock *> *modified_blocks);
  354. void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
  355. ServerEnvironment *env);
  356. void transforming_liquid_add(v3s16 p);
  357. MapSettingsManager settings_mgr;
  358. protected:
  359. void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) override;
  360. private:
  361. friend class LuaVoxelManip;
  362. // Emerge manager
  363. EmergeManager *m_emerge;
  364. std::string m_savedir;
  365. bool m_map_saving_enabled;
  366. int m_map_compression_level;
  367. std::set<v3s16> m_chunks_in_progress;
  368. // Queued transforming water nodes
  369. UniqueQueue<v3s16> m_transforming_liquid;
  370. f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
  371. u32 m_unprocessed_count = 0;
  372. u64 m_inc_trending_up_start_time = 0; // milliseconds
  373. bool m_queue_size_timer_started = false;
  374. /*
  375. Metadata is re-written on disk only if this is true.
  376. This is reset to false when written on disk.
  377. */
  378. bool m_map_metadata_changed = true;
  379. MapDatabase *dbase = nullptr;
  380. MapDatabase *dbase_ro = nullptr;
  381. // Map metrics
  382. MetricGaugePtr m_loaded_blocks_gauge;
  383. MetricCounterPtr m_save_time_counter;
  384. MetricCounterPtr m_save_count_counter;
  385. };
  386. #define VMANIP_BLOCK_DATA_INEXIST 1
  387. #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
  388. class MMVManip : public VoxelManipulator
  389. {
  390. public:
  391. MMVManip(Map *map);
  392. virtual ~MMVManip() = default;
  393. virtual void clear()
  394. {
  395. VoxelManipulator::clear();
  396. m_loaded_blocks.clear();
  397. }
  398. void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
  399. bool load_if_inexistent = true);
  400. // This is much faster with big chunks of generated data
  401. void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
  402. bool overwrite_generated = true);
  403. /*
  404. Creates a copy of this VManip including contents, the copy will not be
  405. associated with a Map.
  406. */
  407. MMVManip *clone() const;
  408. // Reassociates a copied VManip to a map
  409. void reparent(Map *map);
  410. // Is it impossible to call initialEmerge / blitBackAll?
  411. inline bool isOrphan() const { return !m_map; }
  412. bool m_is_dirty = false;
  413. protected:
  414. MMVManip() {};
  415. // may be null
  416. Map *m_map = nullptr;
  417. /*
  418. key = blockpos
  419. value = flags describing the block
  420. */
  421. std::map<v3s16, u8> m_loaded_blocks;
  422. };