map.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  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. #include "map.h"
  17. #include "mapsector.h"
  18. #include "mapblock.h"
  19. #include "filesys.h"
  20. #include "voxel.h"
  21. #include "voxelalgorithms.h"
  22. #include "porting.h"
  23. #include "serialization.h"
  24. #include "nodemetadata.h"
  25. #include "settings.h"
  26. #include "log.h"
  27. #include "profiler.h"
  28. #include "nodedef.h"
  29. #include "gamedef.h"
  30. #include "util/directiontables.h"
  31. #include "util/basic_macros.h"
  32. #include "rollback_interface.h"
  33. #include "environment.h"
  34. #include "reflowscan.h"
  35. #include "emerge.h"
  36. #include "mapgen/mapgen_v6.h"
  37. #include "mapgen/mg_biome.h"
  38. #include "config.h"
  39. #include "server.h"
  40. #include "database/database.h"
  41. #include "database/database-dummy.h"
  42. #include "database/database-sqlite3.h"
  43. #include "script/scripting_server.h"
  44. #include <deque>
  45. #include <queue>
  46. #if USE_LEVELDB
  47. #include "database/database-leveldb.h"
  48. #endif
  49. #if USE_REDIS
  50. #include "database/database-redis.h"
  51. #endif
  52. #if USE_POSTGRESQL
  53. #include "database/database-postgresql.h"
  54. #endif
  55. /*
  56. Map
  57. */
  58. Map::Map(IGameDef *gamedef):
  59. m_gamedef(gamedef),
  60. m_nodedef(gamedef->ndef())
  61. {
  62. }
  63. Map::~Map()
  64. {
  65. /*
  66. Free all MapSectors
  67. */
  68. for (auto &sector : m_sectors) {
  69. delete sector.second;
  70. }
  71. }
  72. void Map::addEventReceiver(MapEventReceiver *event_receiver)
  73. {
  74. m_event_receivers.insert(event_receiver);
  75. }
  76. void Map::removeEventReceiver(MapEventReceiver *event_receiver)
  77. {
  78. m_event_receivers.erase(event_receiver);
  79. }
  80. void Map::dispatchEvent(const MapEditEvent &event)
  81. {
  82. for (MapEventReceiver *event_receiver : m_event_receivers) {
  83. event_receiver->onMapEditEvent(event);
  84. }
  85. }
  86. MapSector * Map::getSectorNoGenerateNoLock(v2s16 p)
  87. {
  88. if(m_sector_cache != NULL && p == m_sector_cache_p){
  89. MapSector * sector = m_sector_cache;
  90. return sector;
  91. }
  92. auto n = m_sectors.find(p);
  93. if (n == m_sectors.end())
  94. return NULL;
  95. MapSector *sector = n->second;
  96. // Cache the last result
  97. m_sector_cache_p = p;
  98. m_sector_cache = sector;
  99. return sector;
  100. }
  101. MapSector * Map::getSectorNoGenerate(v2s16 p)
  102. {
  103. return getSectorNoGenerateNoLock(p);
  104. }
  105. MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d)
  106. {
  107. v2s16 p2d(p3d.X, p3d.Z);
  108. MapSector * sector = getSectorNoGenerate(p2d);
  109. if(sector == NULL)
  110. return NULL;
  111. MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y);
  112. return block;
  113. }
  114. MapBlock * Map::getBlockNoCreate(v3s16 p3d)
  115. {
  116. MapBlock *block = getBlockNoCreateNoEx(p3d);
  117. if(block == NULL)
  118. throw InvalidPositionException();
  119. return block;
  120. }
  121. bool Map::isValidPosition(v3s16 p)
  122. {
  123. v3s16 blockpos = getNodeBlockPos(p);
  124. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  125. return (block != NULL);
  126. }
  127. // Returns a CONTENT_IGNORE node if not found
  128. MapNode Map::getNode(v3s16 p, bool *is_valid_position)
  129. {
  130. v3s16 blockpos = getNodeBlockPos(p);
  131. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  132. if (block == NULL) {
  133. if (is_valid_position != NULL)
  134. *is_valid_position = false;
  135. return {CONTENT_IGNORE};
  136. }
  137. v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
  138. bool is_valid_p;
  139. MapNode node = block->getNodeNoCheck(relpos, &is_valid_p);
  140. if (is_valid_position != NULL)
  141. *is_valid_position = is_valid_p;
  142. return node;
  143. }
  144. static void set_node_in_block(MapBlock *block, v3s16 relpos, MapNode n)
  145. {
  146. // Never allow placing CONTENT_IGNORE, it causes problems
  147. if(n.getContent() == CONTENT_IGNORE){
  148. const NodeDefManager *nodedef = block->getParent()->getNodeDefManager();
  149. v3s16 blockpos = block->getPos();
  150. v3s16 p = blockpos * MAP_BLOCKSIZE + relpos;
  151. bool temp_bool;
  152. errorstream<<"Not allowing to place CONTENT_IGNORE"
  153. <<" while trying to replace \""
  154. <<nodedef->get(block->getNodeNoCheck(relpos, &temp_bool)).name
  155. <<"\" at "<<PP(p)<<" (block "<<PP(blockpos)<<")"<<std::endl;
  156. return;
  157. }
  158. block->setNodeNoCheck(relpos, n);
  159. }
  160. // throws InvalidPositionException if not found
  161. void Map::setNode(v3s16 p, MapNode n)
  162. {
  163. v3s16 blockpos = getNodeBlockPos(p);
  164. MapBlock *block = getBlockNoCreate(blockpos);
  165. v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
  166. set_node_in_block(block, relpos, n);
  167. }
  168. void Map::addNodeAndUpdate(v3s16 p, MapNode n,
  169. std::map<v3s16, MapBlock*> &modified_blocks,
  170. bool remove_metadata)
  171. {
  172. // Collect old node for rollback
  173. RollbackNode rollback_oldnode(this, p, m_gamedef);
  174. v3s16 blockpos = getNodeBlockPos(p);
  175. MapBlock *block = getBlockNoCreate(blockpos);
  176. if (block->isDummy())
  177. throw InvalidPositionException();
  178. v3s16 relpos = p - blockpos * MAP_BLOCKSIZE;
  179. // This is needed for updating the lighting
  180. MapNode oldnode = block->getNodeUnsafe(relpos);
  181. // Remove node metadata
  182. if (remove_metadata) {
  183. removeNodeMetadata(p);
  184. }
  185. // Set the node on the map
  186. const ContentFeatures &cf = m_nodedef->get(n);
  187. const ContentFeatures &oldcf = m_nodedef->get(oldnode);
  188. if (cf.lightingEquivalent(oldcf)) {
  189. // No light update needed, just copy over the old light.
  190. n.setLight(LIGHTBANK_DAY, oldnode.getLightRaw(LIGHTBANK_DAY, oldcf), cf);
  191. n.setLight(LIGHTBANK_NIGHT, oldnode.getLightRaw(LIGHTBANK_NIGHT, oldcf), cf);
  192. set_node_in_block(block, relpos, n);
  193. modified_blocks[blockpos] = block;
  194. } else {
  195. // Ignore light (because calling voxalgo::update_lighting_nodes)
  196. n.setLight(LIGHTBANK_DAY, 0, cf);
  197. n.setLight(LIGHTBANK_NIGHT, 0, cf);
  198. set_node_in_block(block, relpos, n);
  199. // Update lighting
  200. std::vector<std::pair<v3s16, MapNode> > oldnodes;
  201. oldnodes.emplace_back(p, oldnode);
  202. voxalgo::update_lighting_nodes(this, oldnodes, modified_blocks);
  203. for (auto &modified_block : modified_blocks) {
  204. modified_block.second->expireDayNightDiff();
  205. }
  206. }
  207. // Report for rollback
  208. if(m_gamedef->rollback())
  209. {
  210. RollbackNode rollback_newnode(this, p, m_gamedef);
  211. RollbackAction action;
  212. action.setSetNode(p, rollback_oldnode, rollback_newnode);
  213. m_gamedef->rollback()->reportAction(action);
  214. }
  215. }
  216. void Map::removeNodeAndUpdate(v3s16 p,
  217. std::map<v3s16, MapBlock*> &modified_blocks)
  218. {
  219. addNodeAndUpdate(p, MapNode(CONTENT_AIR), modified_blocks, true);
  220. }
  221. bool Map::addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata)
  222. {
  223. MapEditEvent event;
  224. event.type = remove_metadata ? MEET_ADDNODE : MEET_SWAPNODE;
  225. event.p = p;
  226. event.n = n;
  227. bool succeeded = true;
  228. try{
  229. std::map<v3s16, MapBlock*> modified_blocks;
  230. addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
  231. // Copy modified_blocks to event
  232. for (auto &modified_block : modified_blocks) {
  233. event.modified_blocks.insert(modified_block.first);
  234. }
  235. }
  236. catch(InvalidPositionException &e){
  237. succeeded = false;
  238. }
  239. dispatchEvent(event);
  240. return succeeded;
  241. }
  242. bool Map::removeNodeWithEvent(v3s16 p)
  243. {
  244. MapEditEvent event;
  245. event.type = MEET_REMOVENODE;
  246. event.p = p;
  247. bool succeeded = true;
  248. try{
  249. std::map<v3s16, MapBlock*> modified_blocks;
  250. removeNodeAndUpdate(p, modified_blocks);
  251. // Copy modified_blocks to event
  252. for (auto &modified_block : modified_blocks) {
  253. event.modified_blocks.insert(modified_block.first);
  254. }
  255. }
  256. catch(InvalidPositionException &e){
  257. succeeded = false;
  258. }
  259. dispatchEvent(event);
  260. return succeeded;
  261. }
  262. struct TimeOrderedMapBlock {
  263. MapSector *sect;
  264. MapBlock *block;
  265. TimeOrderedMapBlock(MapSector *sect, MapBlock *block) :
  266. sect(sect),
  267. block(block)
  268. {}
  269. bool operator<(const TimeOrderedMapBlock &b) const
  270. {
  271. return block->getUsageTimer() < b.block->getUsageTimer();
  272. };
  273. };
  274. /*
  275. Updates usage timers
  276. */
  277. void Map::timerUpdate(float dtime, float unload_timeout, s32 max_loaded_blocks,
  278. std::vector<v3s16> *unloaded_blocks)
  279. {
  280. bool save_before_unloading = maySaveBlocks();
  281. // Profile modified reasons
  282. Profiler modprofiler;
  283. std::vector<v2s16> sector_deletion_queue;
  284. u32 deleted_blocks_count = 0;
  285. u32 saved_blocks_count = 0;
  286. u32 block_count_all = 0;
  287. const auto start_time = porting::getTimeUs();
  288. beginSave();
  289. // If there is no practical limit, we spare creation of mapblock_queue
  290. if (max_loaded_blocks < 0) {
  291. for (auto &sector_it : m_sectors) {
  292. MapSector *sector = sector_it.second;
  293. bool all_blocks_deleted = true;
  294. MapBlockVect blocks;
  295. sector->getBlocks(blocks);
  296. for (MapBlock *block : blocks) {
  297. block->incrementUsageTimer(dtime);
  298. if (block->refGet() == 0
  299. && block->getUsageTimer() > unload_timeout) {
  300. v3s16 p = block->getPos();
  301. // Save if modified
  302. if (block->getModified() != MOD_STATE_CLEAN
  303. && save_before_unloading) {
  304. modprofiler.add(block->getModifiedReasonString(), 1);
  305. if (!saveBlock(block))
  306. continue;
  307. saved_blocks_count++;
  308. }
  309. // Delete from memory
  310. sector->deleteBlock(block);
  311. if (unloaded_blocks)
  312. unloaded_blocks->push_back(p);
  313. deleted_blocks_count++;
  314. } else {
  315. all_blocks_deleted = false;
  316. block_count_all++;
  317. }
  318. }
  319. // Delete sector if we emptied it
  320. if (all_blocks_deleted) {
  321. sector_deletion_queue.push_back(sector_it.first);
  322. }
  323. }
  324. } else {
  325. std::priority_queue<TimeOrderedMapBlock> mapblock_queue;
  326. for (auto &sector_it : m_sectors) {
  327. MapSector *sector = sector_it.second;
  328. MapBlockVect blocks;
  329. sector->getBlocks(blocks);
  330. for (MapBlock *block : blocks) {
  331. block->incrementUsageTimer(dtime);
  332. mapblock_queue.push(TimeOrderedMapBlock(sector, block));
  333. }
  334. }
  335. block_count_all = mapblock_queue.size();
  336. // Delete old blocks, and blocks over the limit from the memory
  337. while (!mapblock_queue.empty() && ((s32)mapblock_queue.size() > max_loaded_blocks
  338. || mapblock_queue.top().block->getUsageTimer() > unload_timeout)) {
  339. TimeOrderedMapBlock b = mapblock_queue.top();
  340. mapblock_queue.pop();
  341. MapBlock *block = b.block;
  342. if (block->refGet() != 0)
  343. continue;
  344. v3s16 p = block->getPos();
  345. // Save if modified
  346. if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) {
  347. modprofiler.add(block->getModifiedReasonString(), 1);
  348. if (!saveBlock(block))
  349. continue;
  350. saved_blocks_count++;
  351. }
  352. // Delete from memory
  353. b.sect->deleteBlock(block);
  354. if (unloaded_blocks)
  355. unloaded_blocks->push_back(p);
  356. deleted_blocks_count++;
  357. block_count_all--;
  358. }
  359. // Delete empty sectors
  360. for (auto &sector_it : m_sectors) {
  361. if (sector_it.second->empty()) {
  362. sector_deletion_queue.push_back(sector_it.first);
  363. }
  364. }
  365. }
  366. endSave();
  367. const auto end_time = porting::getTimeUs();
  368. reportMetrics(end_time - start_time, saved_blocks_count, block_count_all);
  369. // Finally delete the empty sectors
  370. deleteSectors(sector_deletion_queue);
  371. if(deleted_blocks_count != 0)
  372. {
  373. PrintInfo(infostream); // ServerMap/ClientMap:
  374. infostream<<"Unloaded "<<deleted_blocks_count
  375. <<" blocks from memory";
  376. if(save_before_unloading)
  377. infostream<<", of which "<<saved_blocks_count<<" were written";
  378. infostream<<", "<<block_count_all<<" blocks in memory";
  379. infostream<<"."<<std::endl;
  380. if(saved_blocks_count != 0){
  381. PrintInfo(infostream); // ServerMap/ClientMap:
  382. infostream<<"Blocks modified by: "<<std::endl;
  383. modprofiler.print(infostream);
  384. }
  385. }
  386. }
  387. void Map::unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks)
  388. {
  389. timerUpdate(0.0, -1.0, 0, unloaded_blocks);
  390. }
  391. void Map::deleteSectors(std::vector<v2s16> &sectorList)
  392. {
  393. for (v2s16 j : sectorList) {
  394. MapSector *sector = m_sectors[j];
  395. // If sector is in sector cache, remove it from there
  396. if(m_sector_cache == sector)
  397. m_sector_cache = NULL;
  398. // Remove from map and delete
  399. m_sectors.erase(j);
  400. delete sector;
  401. }
  402. }
  403. void Map::PrintInfo(std::ostream &out)
  404. {
  405. out<<"Map: ";
  406. }
  407. #define WATER_DROP_BOOST 4
  408. const static v3s16 liquid_6dirs[6] = {
  409. // order: upper before same level before lower
  410. v3s16( 0, 1, 0),
  411. v3s16( 0, 0, 1),
  412. v3s16( 1, 0, 0),
  413. v3s16( 0, 0,-1),
  414. v3s16(-1, 0, 0),
  415. v3s16( 0,-1, 0)
  416. };
  417. enum NeighborType : u8 {
  418. NEIGHBOR_UPPER,
  419. NEIGHBOR_SAME_LEVEL,
  420. NEIGHBOR_LOWER
  421. };
  422. struct NodeNeighbor {
  423. MapNode n;
  424. NeighborType t;
  425. v3s16 p;
  426. NodeNeighbor()
  427. : n(CONTENT_AIR), t(NEIGHBOR_SAME_LEVEL)
  428. { }
  429. NodeNeighbor(const MapNode &node, NeighborType n_type, const v3s16 &pos)
  430. : n(node),
  431. t(n_type),
  432. p(pos)
  433. { }
  434. };
  435. void ServerMap::transforming_liquid_add(v3s16 p) {
  436. m_transforming_liquid.push_back(p);
  437. }
  438. void ServerMap::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks,
  439. ServerEnvironment *env)
  440. {
  441. u32 loopcount = 0;
  442. u32 initial_size = m_transforming_liquid.size();
  443. /*if(initial_size != 0)
  444. infostream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;*/
  445. // list of nodes that due to viscosity have not reached their max level height
  446. std::vector<v3s16> must_reflow;
  447. std::vector<std::pair<v3s16, MapNode> > changed_nodes;
  448. u32 liquid_loop_max = g_settings->getS32("liquid_loop_max");
  449. u32 loop_max = liquid_loop_max;
  450. while (m_transforming_liquid.size() != 0)
  451. {
  452. // This should be done here so that it is done when continue is used
  453. if (loopcount >= initial_size || loopcount >= loop_max)
  454. break;
  455. loopcount++;
  456. /*
  457. Get a queued transforming liquid node
  458. */
  459. v3s16 p0 = m_transforming_liquid.front();
  460. m_transforming_liquid.pop_front();
  461. MapNode n0 = getNode(p0);
  462. /*
  463. Collect information about current node
  464. */
  465. s8 liquid_level = -1;
  466. // The liquid node which will be placed there if
  467. // the liquid flows into this node.
  468. content_t liquid_kind = CONTENT_IGNORE;
  469. // The node which will be placed there if liquid
  470. // can't flow into this node.
  471. content_t floodable_node = CONTENT_AIR;
  472. const ContentFeatures &cf = m_nodedef->get(n0);
  473. LiquidType liquid_type = cf.liquid_type;
  474. switch (liquid_type) {
  475. case LIQUID_SOURCE:
  476. liquid_level = LIQUID_LEVEL_SOURCE;
  477. liquid_kind = cf.liquid_alternative_flowing_id;
  478. break;
  479. case LIQUID_FLOWING:
  480. liquid_level = (n0.param2 & LIQUID_LEVEL_MASK);
  481. liquid_kind = n0.getContent();
  482. break;
  483. case LIQUID_NONE:
  484. // if this node is 'floodable', it *could* be transformed
  485. // into a liquid, otherwise, continue with the next node.
  486. if (!cf.floodable)
  487. continue;
  488. floodable_node = n0.getContent();
  489. liquid_kind = CONTENT_AIR;
  490. break;
  491. }
  492. /*
  493. Collect information about the environment
  494. */
  495. NodeNeighbor sources[6]; // surrounding sources
  496. int num_sources = 0;
  497. NodeNeighbor flows[6]; // surrounding flowing liquid nodes
  498. int num_flows = 0;
  499. NodeNeighbor airs[6]; // surrounding air
  500. int num_airs = 0;
  501. NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid
  502. int num_neutrals = 0;
  503. bool flowing_down = false;
  504. bool ignored_sources = false;
  505. for (u16 i = 0; i < 6; i++) {
  506. NeighborType nt = NEIGHBOR_SAME_LEVEL;
  507. switch (i) {
  508. case 0:
  509. nt = NEIGHBOR_UPPER;
  510. break;
  511. case 5:
  512. nt = NEIGHBOR_LOWER;
  513. break;
  514. default:
  515. break;
  516. }
  517. v3s16 npos = p0 + liquid_6dirs[i];
  518. NodeNeighbor nb(getNode(npos), nt, npos);
  519. const ContentFeatures &cfnb = m_nodedef->get(nb.n);
  520. switch (m_nodedef->get(nb.n.getContent()).liquid_type) {
  521. case LIQUID_NONE:
  522. if (cfnb.floodable) {
  523. airs[num_airs++] = nb;
  524. // if the current node is a water source the neighbor
  525. // should be enqueded for transformation regardless of whether the
  526. // current node changes or not.
  527. if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE)
  528. m_transforming_liquid.push_back(npos);
  529. // if the current node happens to be a flowing node, it will start to flow down here.
  530. if (nb.t == NEIGHBOR_LOWER)
  531. flowing_down = true;
  532. } else {
  533. neutrals[num_neutrals++] = nb;
  534. if (nb.n.getContent() == CONTENT_IGNORE) {
  535. // If node below is ignore prevent water from
  536. // spreading outwards and otherwise prevent from
  537. // flowing away as ignore node might be the source
  538. if (nb.t == NEIGHBOR_LOWER)
  539. flowing_down = true;
  540. else
  541. ignored_sources = true;
  542. }
  543. }
  544. break;
  545. case LIQUID_SOURCE:
  546. // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
  547. if (liquid_kind == CONTENT_AIR)
  548. liquid_kind = cfnb.liquid_alternative_flowing_id;
  549. if (cfnb.liquid_alternative_flowing_id != liquid_kind) {
  550. neutrals[num_neutrals++] = nb;
  551. } else {
  552. // Do not count bottom source, it will screw things up
  553. if(nt != NEIGHBOR_LOWER)
  554. sources[num_sources++] = nb;
  555. }
  556. break;
  557. case LIQUID_FLOWING:
  558. if (nb.t != NEIGHBOR_SAME_LEVEL ||
  559. (nb.n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK) {
  560. // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
  561. // but exclude falling liquids on the same level, they cannot flow here anyway
  562. if (liquid_kind == CONTENT_AIR)
  563. liquid_kind = cfnb.liquid_alternative_flowing_id;
  564. }
  565. if (cfnb.liquid_alternative_flowing_id != liquid_kind) {
  566. neutrals[num_neutrals++] = nb;
  567. } else {
  568. flows[num_flows++] = nb;
  569. if (nb.t == NEIGHBOR_LOWER)
  570. flowing_down = true;
  571. }
  572. break;
  573. }
  574. }
  575. /*
  576. decide on the type (and possibly level) of the current node
  577. */
  578. content_t new_node_content;
  579. s8 new_node_level = -1;
  580. s8 max_node_level = -1;
  581. u8 range = m_nodedef->get(liquid_kind).liquid_range;
  582. if (range > LIQUID_LEVEL_MAX + 1)
  583. range = LIQUID_LEVEL_MAX + 1;
  584. if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) {
  585. // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid)
  586. // or the flowing alternative of the first of the surrounding sources (if it's air), so
  587. // it's perfectly safe to use liquid_kind here to determine the new node content.
  588. new_node_content = m_nodedef->get(liquid_kind).liquid_alternative_source_id;
  589. } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) {
  590. // liquid_kind is set properly, see above
  591. max_node_level = new_node_level = LIQUID_LEVEL_MAX;
  592. if (new_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
  593. new_node_content = liquid_kind;
  594. else
  595. new_node_content = floodable_node;
  596. } else if (ignored_sources && liquid_level >= 0) {
  597. // Maybe there are neighbouring sources that aren't loaded yet
  598. // so prevent flowing away.
  599. new_node_level = liquid_level;
  600. new_node_content = liquid_kind;
  601. } else {
  602. // no surrounding sources, so get the maximum level that can flow into this node
  603. for (u16 i = 0; i < num_flows; i++) {
  604. u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK);
  605. switch (flows[i].t) {
  606. case NEIGHBOR_UPPER:
  607. if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) {
  608. max_node_level = LIQUID_LEVEL_MAX;
  609. if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX)
  610. max_node_level = nb_liquid_level + WATER_DROP_BOOST;
  611. } else if (nb_liquid_level > max_node_level) {
  612. max_node_level = nb_liquid_level;
  613. }
  614. break;
  615. case NEIGHBOR_LOWER:
  616. break;
  617. case NEIGHBOR_SAME_LEVEL:
  618. if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK &&
  619. nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level)
  620. max_node_level = nb_liquid_level - 1;
  621. break;
  622. }
  623. }
  624. u8 viscosity = m_nodedef->get(liquid_kind).liquid_viscosity;
  625. if (viscosity > 1 && max_node_level != liquid_level) {
  626. // amount to gain, limited by viscosity
  627. // must be at least 1 in absolute value
  628. s8 level_inc = max_node_level - liquid_level;
  629. if (level_inc < -viscosity || level_inc > viscosity)
  630. new_node_level = liquid_level + level_inc/viscosity;
  631. else if (level_inc < 0)
  632. new_node_level = liquid_level - 1;
  633. else if (level_inc > 0)
  634. new_node_level = liquid_level + 1;
  635. if (new_node_level != max_node_level)
  636. must_reflow.push_back(p0);
  637. } else {
  638. new_node_level = max_node_level;
  639. }
  640. if (max_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
  641. new_node_content = liquid_kind;
  642. else
  643. new_node_content = floodable_node;
  644. }
  645. /*
  646. check if anything has changed. if not, just continue with the next node.
  647. */
  648. if (new_node_content == n0.getContent() &&
  649. (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING ||
  650. ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level &&
  651. ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK)
  652. == flowing_down)))
  653. continue;
  654. /*
  655. update the current node
  656. */
  657. MapNode n00 = n0;
  658. //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK));
  659. if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) {
  660. // set level to last 3 bits, flowing down bit to 4th bit
  661. n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK);
  662. } else {
  663. // set the liquid level and flow bits to 0
  664. n0.param2 &= ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK);
  665. }
  666. // change the node.
  667. n0.setContent(new_node_content);
  668. // on_flood() the node
  669. if (floodable_node != CONTENT_AIR) {
  670. if (env->getScriptIface()->node_on_flood(p0, n00, n0))
  671. continue;
  672. }
  673. // Ignore light (because calling voxalgo::update_lighting_nodes)
  674. n0.setLight(LIGHTBANK_DAY, 0, m_nodedef);
  675. n0.setLight(LIGHTBANK_NIGHT, 0, m_nodedef);
  676. // Find out whether there is a suspect for this action
  677. std::string suspect;
  678. if (m_gamedef->rollback())
  679. suspect = m_gamedef->rollback()->getSuspect(p0, 83, 1);
  680. if (m_gamedef->rollback() && !suspect.empty()) {
  681. // Blame suspect
  682. RollbackScopeActor rollback_scope(m_gamedef->rollback(), suspect, true);
  683. // Get old node for rollback
  684. RollbackNode rollback_oldnode(this, p0, m_gamedef);
  685. // Set node
  686. setNode(p0, n0);
  687. // Report
  688. RollbackNode rollback_newnode(this, p0, m_gamedef);
  689. RollbackAction action;
  690. action.setSetNode(p0, rollback_oldnode, rollback_newnode);
  691. m_gamedef->rollback()->reportAction(action);
  692. } else {
  693. // Set node
  694. setNode(p0, n0);
  695. }
  696. v3s16 blockpos = getNodeBlockPos(p0);
  697. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  698. if (block != NULL) {
  699. modified_blocks[blockpos] = block;
  700. changed_nodes.emplace_back(p0, n00);
  701. }
  702. /*
  703. enqueue neighbors for update if neccessary
  704. */
  705. switch (m_nodedef->get(n0.getContent()).liquid_type) {
  706. case LIQUID_SOURCE:
  707. case LIQUID_FLOWING:
  708. // make sure source flows into all neighboring nodes
  709. for (u16 i = 0; i < num_flows; i++)
  710. if (flows[i].t != NEIGHBOR_UPPER)
  711. m_transforming_liquid.push_back(flows[i].p);
  712. for (u16 i = 0; i < num_airs; i++)
  713. if (airs[i].t != NEIGHBOR_UPPER)
  714. m_transforming_liquid.push_back(airs[i].p);
  715. break;
  716. case LIQUID_NONE:
  717. // this flow has turned to air; neighboring flows might need to do the same
  718. for (u16 i = 0; i < num_flows; i++)
  719. m_transforming_liquid.push_back(flows[i].p);
  720. break;
  721. }
  722. }
  723. //infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl;
  724. for (const auto &iter : must_reflow)
  725. m_transforming_liquid.push_back(iter);
  726. voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks);
  727. env->getScriptIface()->on_liquid_transformed(changed_nodes);
  728. /* ----------------------------------------------------------------------
  729. * Manage the queue so that it does not grow indefinately
  730. */
  731. u16 time_until_purge = g_settings->getU16("liquid_queue_purge_time");
  732. if (time_until_purge == 0)
  733. return; // Feature disabled
  734. time_until_purge *= 1000; // seconds -> milliseconds
  735. u64 curr_time = porting::getTimeMs();
  736. u32 prev_unprocessed = m_unprocessed_count;
  737. m_unprocessed_count = m_transforming_liquid.size();
  738. // if unprocessed block count is decreasing or stable
  739. if (m_unprocessed_count <= prev_unprocessed) {
  740. m_queue_size_timer_started = false;
  741. } else {
  742. if (!m_queue_size_timer_started)
  743. m_inc_trending_up_start_time = curr_time;
  744. m_queue_size_timer_started = true;
  745. }
  746. // Account for curr_time overflowing
  747. if (m_queue_size_timer_started && m_inc_trending_up_start_time > curr_time)
  748. m_queue_size_timer_started = false;
  749. /* If the queue has been growing for more than liquid_queue_purge_time seconds
  750. * and the number of unprocessed blocks is still > liquid_loop_max then we
  751. * cannot keep up; dump the oldest blocks from the queue so that the queue
  752. * has liquid_loop_max items in it
  753. */
  754. if (m_queue_size_timer_started
  755. && curr_time - m_inc_trending_up_start_time > time_until_purge
  756. && m_unprocessed_count > liquid_loop_max) {
  757. size_t dump_qty = m_unprocessed_count - liquid_loop_max;
  758. infostream << "transformLiquids(): DUMPING " << dump_qty
  759. << " blocks from the queue" << std::endl;
  760. while (dump_qty--)
  761. m_transforming_liquid.pop_front();
  762. m_queue_size_timer_started = false; // optimistically assume we can keep up now
  763. m_unprocessed_count = m_transforming_liquid.size();
  764. }
  765. }
  766. std::vector<v3s16> Map::findNodesWithMetadata(v3s16 p1, v3s16 p2)
  767. {
  768. std::vector<v3s16> positions_with_meta;
  769. sortBoxVerticies(p1, p2);
  770. v3s16 bpmin = getNodeBlockPos(p1);
  771. v3s16 bpmax = getNodeBlockPos(p2);
  772. VoxelArea area(p1, p2);
  773. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  774. for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
  775. for (s16 x = bpmin.X; x <= bpmax.X; x++) {
  776. v3s16 blockpos(x, y, z);
  777. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  778. if (!block) {
  779. verbosestream << "Map::getNodeMetadata(): Need to emerge "
  780. << PP(blockpos) << std::endl;
  781. block = emergeBlock(blockpos, false);
  782. }
  783. if (!block) {
  784. infostream << "WARNING: Map::getNodeMetadata(): Block not found"
  785. << std::endl;
  786. continue;
  787. }
  788. v3s16 p_base = blockpos * MAP_BLOCKSIZE;
  789. std::vector<v3s16> keys = block->m_node_metadata.getAllKeys();
  790. for (size_t i = 0; i != keys.size(); i++) {
  791. v3s16 p(keys[i] + p_base);
  792. if (!area.contains(p))
  793. continue;
  794. positions_with_meta.push_back(p);
  795. }
  796. }
  797. return positions_with_meta;
  798. }
  799. NodeMetadata *Map::getNodeMetadata(v3s16 p)
  800. {
  801. v3s16 blockpos = getNodeBlockPos(p);
  802. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  803. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  804. if(!block){
  805. infostream<<"Map::getNodeMetadata(): Need to emerge "
  806. <<PP(blockpos)<<std::endl;
  807. block = emergeBlock(blockpos, false);
  808. }
  809. if(!block){
  810. warningstream<<"Map::getNodeMetadata(): Block not found"
  811. <<std::endl;
  812. return NULL;
  813. }
  814. NodeMetadata *meta = block->m_node_metadata.get(p_rel);
  815. return meta;
  816. }
  817. bool Map::setNodeMetadata(v3s16 p, NodeMetadata *meta)
  818. {
  819. v3s16 blockpos = getNodeBlockPos(p);
  820. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  821. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  822. if(!block){
  823. infostream<<"Map::setNodeMetadata(): Need to emerge "
  824. <<PP(blockpos)<<std::endl;
  825. block = emergeBlock(blockpos, false);
  826. }
  827. if(!block){
  828. warningstream<<"Map::setNodeMetadata(): Block not found"
  829. <<std::endl;
  830. return false;
  831. }
  832. block->m_node_metadata.set(p_rel, meta);
  833. return true;
  834. }
  835. void Map::removeNodeMetadata(v3s16 p)
  836. {
  837. v3s16 blockpos = getNodeBlockPos(p);
  838. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  839. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  840. if(block == NULL)
  841. {
  842. warningstream<<"Map::removeNodeMetadata(): Block not found"
  843. <<std::endl;
  844. return;
  845. }
  846. block->m_node_metadata.remove(p_rel);
  847. }
  848. NodeTimer Map::getNodeTimer(v3s16 p)
  849. {
  850. v3s16 blockpos = getNodeBlockPos(p);
  851. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  852. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  853. if(!block){
  854. infostream<<"Map::getNodeTimer(): Need to emerge "
  855. <<PP(blockpos)<<std::endl;
  856. block = emergeBlock(blockpos, false);
  857. }
  858. if(!block){
  859. warningstream<<"Map::getNodeTimer(): Block not found"
  860. <<std::endl;
  861. return NodeTimer();
  862. }
  863. NodeTimer t = block->m_node_timers.get(p_rel);
  864. NodeTimer nt(t.timeout, t.elapsed, p);
  865. return nt;
  866. }
  867. void Map::setNodeTimer(const NodeTimer &t)
  868. {
  869. v3s16 p = t.position;
  870. v3s16 blockpos = getNodeBlockPos(p);
  871. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  872. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  873. if(!block){
  874. infostream<<"Map::setNodeTimer(): Need to emerge "
  875. <<PP(blockpos)<<std::endl;
  876. block = emergeBlock(blockpos, false);
  877. }
  878. if(!block){
  879. warningstream<<"Map::setNodeTimer(): Block not found"
  880. <<std::endl;
  881. return;
  882. }
  883. NodeTimer nt(t.timeout, t.elapsed, p_rel);
  884. block->m_node_timers.set(nt);
  885. }
  886. void Map::removeNodeTimer(v3s16 p)
  887. {
  888. v3s16 blockpos = getNodeBlockPos(p);
  889. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  890. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  891. if(block == NULL)
  892. {
  893. warningstream<<"Map::removeNodeTimer(): Block not found"
  894. <<std::endl;
  895. return;
  896. }
  897. block->m_node_timers.remove(p_rel);
  898. }
  899. bool Map::determineAdditionalOcclusionCheck(const v3s16 &pos_camera,
  900. const core::aabbox3d<s16> &block_bounds, v3s16 &check)
  901. {
  902. /*
  903. This functions determines the node inside the target block that is
  904. closest to the camera position. This increases the occlusion culling
  905. accuracy in straight and diagonal corridors.
  906. The returned position will be occlusion checked first in addition to the
  907. others (8 corners + center).
  908. No position is returned if
  909. - the closest node is a corner, corners are checked anyway.
  910. - the camera is inside the target block, it will never be occluded.
  911. */
  912. #define CLOSEST_EDGE(pos, bounds, axis) \
  913. ((pos).axis <= (bounds).MinEdge.axis) ? (bounds).MinEdge.axis : \
  914. (bounds).MaxEdge.axis
  915. bool x_inside = (block_bounds.MinEdge.X <= pos_camera.X) &&
  916. (pos_camera.X <= block_bounds.MaxEdge.X);
  917. bool y_inside = (block_bounds.MinEdge.Y <= pos_camera.Y) &&
  918. (pos_camera.Y <= block_bounds.MaxEdge.Y);
  919. bool z_inside = (block_bounds.MinEdge.Z <= pos_camera.Z) &&
  920. (pos_camera.Z <= block_bounds.MaxEdge.Z);
  921. if (x_inside && y_inside && z_inside)
  922. return false; // Camera inside target mapblock
  923. // straight
  924. if (x_inside && y_inside) {
  925. check = v3s16(pos_camera.X, pos_camera.Y, 0);
  926. check.Z = CLOSEST_EDGE(pos_camera, block_bounds, Z);
  927. return true;
  928. } else if (y_inside && z_inside) {
  929. check = v3s16(0, pos_camera.Y, pos_camera.Z);
  930. check.X = CLOSEST_EDGE(pos_camera, block_bounds, X);
  931. return true;
  932. } else if (x_inside && z_inside) {
  933. check = v3s16(pos_camera.X, 0, pos_camera.Z);
  934. check.Y = CLOSEST_EDGE(pos_camera, block_bounds, Y);
  935. return true;
  936. }
  937. // diagonal
  938. if (x_inside) {
  939. check = v3s16(pos_camera.X, 0, 0);
  940. check.Y = CLOSEST_EDGE(pos_camera, block_bounds, Y);
  941. check.Z = CLOSEST_EDGE(pos_camera, block_bounds, Z);
  942. return true;
  943. } else if (y_inside) {
  944. check = v3s16(0, pos_camera.Y, 0);
  945. check.X = CLOSEST_EDGE(pos_camera, block_bounds, X);
  946. check.Z = CLOSEST_EDGE(pos_camera, block_bounds, Z);
  947. return true;
  948. } else if (z_inside) {
  949. check = v3s16(0, 0, pos_camera.Z);
  950. check.X = CLOSEST_EDGE(pos_camera, block_bounds, X);
  951. check.Y = CLOSEST_EDGE(pos_camera, block_bounds, Y);
  952. return true;
  953. }
  954. // Closest node would be a corner, none returned
  955. return false;
  956. }
  957. bool Map::isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target,
  958. float step, float stepfac, float offset, float end_offset, u32 needed_count)
  959. {
  960. v3f direction = intToFloat(pos_target - pos_camera, BS);
  961. float distance = direction.getLength();
  962. // Normalize direction vector
  963. if (distance > 0.0f)
  964. direction /= distance;
  965. v3f pos_origin_f = intToFloat(pos_camera, BS);
  966. u32 count = 0;
  967. bool is_valid_position;
  968. for (; offset < distance + end_offset; offset += step) {
  969. v3f pos_node_f = pos_origin_f + direction * offset;
  970. v3s16 pos_node = floatToInt(pos_node_f, BS);
  971. MapNode node = getNode(pos_node, &is_valid_position);
  972. if (is_valid_position &&
  973. !m_nodedef->get(node).light_propagates) {
  974. // Cannot see through light-blocking nodes --> occluded
  975. count++;
  976. if (count >= needed_count)
  977. return true;
  978. }
  979. step *= stepfac;
  980. }
  981. return false;
  982. }
  983. bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes)
  984. {
  985. // Check occlusion for center and all 8 corners of the mapblock
  986. // Overshoot a little for less flickering
  987. static const s16 bs2 = MAP_BLOCKSIZE / 2 + 1;
  988. static const v3s16 dir9[9] = {
  989. v3s16( 0, 0, 0),
  990. v3s16( 1, 1, 1) * bs2,
  991. v3s16( 1, 1, -1) * bs2,
  992. v3s16( 1, -1, 1) * bs2,
  993. v3s16( 1, -1, -1) * bs2,
  994. v3s16(-1, 1, 1) * bs2,
  995. v3s16(-1, 1, -1) * bs2,
  996. v3s16(-1, -1, 1) * bs2,
  997. v3s16(-1, -1, -1) * bs2,
  998. };
  999. v3s16 pos_blockcenter = block->getPosRelative() + (MAP_BLOCKSIZE / 2);
  1000. // Starting step size, value between 1m and sqrt(3)m
  1001. float step = BS * 1.2f;
  1002. // Multiply step by each iteraction by 'stepfac' to reduce checks in distance
  1003. float stepfac = 1.05f;
  1004. float start_offset = BS * 1.0f;
  1005. // The occlusion search of 'isOccluded()' must stop short of the target
  1006. // point by distance 'end_offset' to not enter the target mapblock.
  1007. // For the 8 mapblock corners 'end_offset' must therefore be the maximum
  1008. // diagonal of a mapblock, because we must consider all view angles.
  1009. // sqrt(1^2 + 1^2 + 1^2) = 1.732
  1010. float end_offset = -BS * MAP_BLOCKSIZE * 1.732f;
  1011. // to reduce the likelihood of falsely occluded blocks
  1012. // require at least two solid blocks
  1013. // this is a HACK, we should think of a more precise algorithm
  1014. u32 needed_count = 2;
  1015. // Additional occlusion check, see comments in that function
  1016. v3s16 check;
  1017. if (determineAdditionalOcclusionCheck(cam_pos_nodes, block->getBox(), check)) {
  1018. // node is always on a side facing the camera, end_offset can be lower
  1019. if (!isOccluded(cam_pos_nodes, check, step, stepfac, start_offset,
  1020. -1.0f, needed_count))
  1021. return false;
  1022. }
  1023. for (const v3s16 &dir : dir9) {
  1024. if (!isOccluded(cam_pos_nodes, pos_blockcenter + dir, step, stepfac,
  1025. start_offset, end_offset, needed_count))
  1026. return false;
  1027. }
  1028. return true;
  1029. }
  1030. /*
  1031. ServerMap
  1032. */
  1033. ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef,
  1034. EmergeManager *emerge, MetricsBackend *mb):
  1035. Map(gamedef),
  1036. settings_mgr(savedir + DIR_DELIM + "map_meta.txt"),
  1037. m_emerge(emerge)
  1038. {
  1039. verbosestream<<FUNCTION_NAME<<std::endl;
  1040. // Tell the EmergeManager about our MapSettingsManager
  1041. emerge->map_settings_mgr = &settings_mgr;
  1042. /*
  1043. Try to load map; if not found, create a new one.
  1044. */
  1045. // Determine which database backend to use
  1046. std::string conf_path = savedir + DIR_DELIM + "world.mt";
  1047. Settings conf;
  1048. bool succeeded = conf.readConfigFile(conf_path.c_str());
  1049. if (!succeeded || !conf.exists("backend")) {
  1050. // fall back to sqlite3
  1051. conf.set("backend", "sqlite3");
  1052. }
  1053. std::string backend = conf.get("backend");
  1054. dbase = createDatabase(backend, savedir, conf);
  1055. if (conf.exists("readonly_backend")) {
  1056. std::string readonly_dir = savedir + DIR_DELIM + "readonly";
  1057. dbase_ro = createDatabase(conf.get("readonly_backend"), readonly_dir, conf);
  1058. }
  1059. if (!conf.updateConfigFile(conf_path.c_str()))
  1060. errorstream << "ServerMap::ServerMap(): Failed to update world.mt!" << std::endl;
  1061. m_savedir = savedir;
  1062. m_map_saving_enabled = false;
  1063. m_save_time_counter = mb->addCounter(
  1064. "minetest_map_save_time", "Time spent saving blocks (in microseconds)");
  1065. m_save_count_counter = mb->addCounter(
  1066. "minetest_map_saved_blocks", "Number of blocks saved");
  1067. m_loaded_blocks_gauge = mb->addGauge(
  1068. "minetest_map_loaded_blocks", "Number of loaded blocks");
  1069. m_map_compression_level = rangelim(g_settings->getS16("map_compression_level_disk"), -1, 9);
  1070. try {
  1071. // If directory exists, check contents and load if possible
  1072. if (fs::PathExists(m_savedir)) {
  1073. // If directory is empty, it is safe to save into it.
  1074. if (fs::GetDirListing(m_savedir).empty()) {
  1075. infostream<<"ServerMap: Empty save directory is valid."
  1076. <<std::endl;
  1077. m_map_saving_enabled = true;
  1078. }
  1079. else
  1080. {
  1081. if (settings_mgr.loadMapMeta()) {
  1082. infostream << "ServerMap: Metadata loaded from "
  1083. << savedir << std::endl;
  1084. } else {
  1085. infostream << "ServerMap: Metadata could not be loaded "
  1086. "from " << savedir << ", assuming valid save "
  1087. "directory." << std::endl;
  1088. }
  1089. m_map_saving_enabled = true;
  1090. // Map loaded, not creating new one
  1091. return;
  1092. }
  1093. }
  1094. // If directory doesn't exist, it is safe to save to it
  1095. else{
  1096. m_map_saving_enabled = true;
  1097. }
  1098. }
  1099. catch(std::exception &e)
  1100. {
  1101. warningstream<<"ServerMap: Failed to load map from "<<savedir
  1102. <<", exception: "<<e.what()<<std::endl;
  1103. infostream<<"Please remove the map or fix it."<<std::endl;
  1104. warningstream<<"Map saving will be disabled."<<std::endl;
  1105. }
  1106. }
  1107. ServerMap::~ServerMap()
  1108. {
  1109. verbosestream<<FUNCTION_NAME<<std::endl;
  1110. try
  1111. {
  1112. if (m_map_saving_enabled) {
  1113. // Save only changed parts
  1114. save(MOD_STATE_WRITE_AT_UNLOAD);
  1115. infostream << "ServerMap: Saved map to " << m_savedir << std::endl;
  1116. } else {
  1117. infostream << "ServerMap: Map not saved" << std::endl;
  1118. }
  1119. }
  1120. catch(std::exception &e)
  1121. {
  1122. infostream<<"ServerMap: Failed to save map to "<<m_savedir
  1123. <<", exception: "<<e.what()<<std::endl;
  1124. }
  1125. /*
  1126. Close database if it was opened
  1127. */
  1128. delete dbase;
  1129. delete dbase_ro;
  1130. }
  1131. MapgenParams *ServerMap::getMapgenParams()
  1132. {
  1133. // getMapgenParams() should only ever be called after Server is initialized
  1134. assert(settings_mgr.mapgen_params != NULL);
  1135. return settings_mgr.mapgen_params;
  1136. }
  1137. u64 ServerMap::getSeed()
  1138. {
  1139. return getMapgenParams()->seed;
  1140. }
  1141. bool ServerMap::blockpos_over_mapgen_limit(v3s16 p)
  1142. {
  1143. const s16 mapgen_limit_bp = rangelim(
  1144. getMapgenParams()->mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) /
  1145. MAP_BLOCKSIZE;
  1146. return p.X < -mapgen_limit_bp ||
  1147. p.X > mapgen_limit_bp ||
  1148. p.Y < -mapgen_limit_bp ||
  1149. p.Y > mapgen_limit_bp ||
  1150. p.Z < -mapgen_limit_bp ||
  1151. p.Z > mapgen_limit_bp;
  1152. }
  1153. bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data)
  1154. {
  1155. s16 csize = getMapgenParams()->chunksize;
  1156. v3s16 bpmin = EmergeManager::getContainingChunk(blockpos, csize);
  1157. v3s16 bpmax = bpmin + v3s16(1, 1, 1) * (csize - 1);
  1158. if (!m_chunks_in_progress.insert(bpmin).second)
  1159. return false;
  1160. bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
  1161. EMERGE_DBG_OUT("initBlockMake(): " PP(bpmin) " - " PP(bpmax));
  1162. v3s16 extra_borders(1, 1, 1);
  1163. v3s16 full_bpmin = bpmin - extra_borders;
  1164. v3s16 full_bpmax = bpmax + extra_borders;
  1165. // Do nothing if not inside mapgen limits (+-1 because of neighbors)
  1166. if (blockpos_over_mapgen_limit(full_bpmin) ||
  1167. blockpos_over_mapgen_limit(full_bpmax))
  1168. return false;
  1169. data->seed = getSeed();
  1170. data->blockpos_min = bpmin;
  1171. data->blockpos_max = bpmax;
  1172. data->nodedef = m_nodedef;
  1173. /*
  1174. Create the whole area of this and the neighboring blocks
  1175. */
  1176. for (s16 x = full_bpmin.X; x <= full_bpmax.X; x++)
  1177. for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) {
  1178. v2s16 sectorpos(x, z);
  1179. // Sector metadata is loaded from disk if not already loaded.
  1180. MapSector *sector = createSector(sectorpos);
  1181. FATAL_ERROR_IF(sector == NULL, "createSector() failed");
  1182. for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) {
  1183. v3s16 p(x, y, z);
  1184. MapBlock *block = emergeBlock(p, false);
  1185. if (block == NULL) {
  1186. block = createBlock(p);
  1187. // Block gets sunlight if this is true.
  1188. // Refer to the map generator heuristics.
  1189. bool ug = m_emerge->isBlockUnderground(p);
  1190. block->setIsUnderground(ug);
  1191. }
  1192. }
  1193. }
  1194. /*
  1195. Now we have a big empty area.
  1196. Make a ManualMapVoxelManipulator that contains this and the
  1197. neighboring blocks
  1198. */
  1199. data->vmanip = new MMVManip(this);
  1200. data->vmanip->initialEmerge(full_bpmin, full_bpmax);
  1201. // Data is ready now.
  1202. return true;
  1203. }
  1204. void ServerMap::finishBlockMake(BlockMakeData *data,
  1205. std::map<v3s16, MapBlock*> *changed_blocks)
  1206. {
  1207. v3s16 bpmin = data->blockpos_min;
  1208. v3s16 bpmax = data->blockpos_max;
  1209. bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
  1210. EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax));
  1211. /*
  1212. Blit generated stuff to map
  1213. NOTE: blitBackAll adds nearly everything to changed_blocks
  1214. */
  1215. data->vmanip->blitBackAll(changed_blocks);
  1216. EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()="
  1217. << changed_blocks->size());
  1218. /*
  1219. Copy transforming liquid information
  1220. */
  1221. while (data->transforming_liquid.size()) {
  1222. m_transforming_liquid.push_back(data->transforming_liquid.front());
  1223. data->transforming_liquid.pop_front();
  1224. }
  1225. for (auto &changed_block : *changed_blocks) {
  1226. MapBlock *block = changed_block.second;
  1227. if (!block)
  1228. continue;
  1229. /*
  1230. Update day/night difference cache of the MapBlocks
  1231. */
  1232. block->expireDayNightDiff();
  1233. /*
  1234. Set block as modified
  1235. */
  1236. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1237. MOD_REASON_EXPIRE_DAYNIGHTDIFF);
  1238. }
  1239. /*
  1240. Set central blocks as generated
  1241. */
  1242. for (s16 x = bpmin.X; x <= bpmax.X; x++)
  1243. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  1244. for (s16 y = bpmin.Y; y <= bpmax.Y; y++) {
  1245. MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z));
  1246. if (!block)
  1247. continue;
  1248. block->setGenerated(true);
  1249. }
  1250. /*
  1251. Save changed parts of map
  1252. NOTE: Will be saved later.
  1253. */
  1254. //save(MOD_STATE_WRITE_AT_UNLOAD);
  1255. m_chunks_in_progress.erase(bpmin);
  1256. }
  1257. MapSector *ServerMap::createSector(v2s16 p2d)
  1258. {
  1259. /*
  1260. Check if it exists already in memory
  1261. */
  1262. MapSector *sector = getSectorNoGenerate(p2d);
  1263. if (sector)
  1264. return sector;
  1265. /*
  1266. Do not create over max mapgen limit
  1267. */
  1268. if (blockpos_over_max_limit(v3s16(p2d.X, 0, p2d.Y)))
  1269. throw InvalidPositionException("createSector(): pos. over max mapgen limit");
  1270. /*
  1271. Generate blank sector
  1272. */
  1273. sector = new MapSector(this, p2d, m_gamedef);
  1274. /*
  1275. Insert to container
  1276. */
  1277. m_sectors[p2d] = sector;
  1278. return sector;
  1279. }
  1280. MapBlock * ServerMap::createBlock(v3s16 p)
  1281. {
  1282. /*
  1283. Do not create over max mapgen limit
  1284. */
  1285. if (blockpos_over_max_limit(p))
  1286. throw InvalidPositionException("createBlock(): pos. over max mapgen limit");
  1287. v2s16 p2d(p.X, p.Z);
  1288. s16 block_y = p.Y;
  1289. /*
  1290. This will create or load a sector if not found in memory.
  1291. If block exists on disk, it will be loaded.
  1292. NOTE: On old save formats, this will be slow, as it generates
  1293. lighting on blocks for them.
  1294. */
  1295. MapSector *sector;
  1296. try {
  1297. sector = createSector(p2d);
  1298. } catch (InvalidPositionException &e) {
  1299. infostream<<"createBlock: createSector() failed"<<std::endl;
  1300. throw e;
  1301. }
  1302. /*
  1303. Try to get a block from the sector
  1304. */
  1305. MapBlock *block = sector->getBlockNoCreateNoEx(block_y);
  1306. if (block) {
  1307. if(block->isDummy())
  1308. block->unDummify();
  1309. return block;
  1310. }
  1311. // Create blank
  1312. block = sector->createBlankBlock(block_y);
  1313. return block;
  1314. }
  1315. MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank)
  1316. {
  1317. {
  1318. MapBlock *block = getBlockNoCreateNoEx(p);
  1319. if (block && !block->isDummy())
  1320. return block;
  1321. }
  1322. {
  1323. MapBlock *block = loadBlock(p);
  1324. if(block)
  1325. return block;
  1326. }
  1327. if (create_blank) {
  1328. MapSector *sector = createSector(v2s16(p.X, p.Z));
  1329. MapBlock *block = sector->createBlankBlock(p.Y);
  1330. return block;
  1331. }
  1332. return NULL;
  1333. }
  1334. MapBlock *ServerMap::getBlockOrEmerge(v3s16 p3d)
  1335. {
  1336. MapBlock *block = getBlockNoCreateNoEx(p3d);
  1337. if (block == NULL)
  1338. m_emerge->enqueueBlockEmerge(PEER_ID_INEXISTENT, p3d, false);
  1339. return block;
  1340. }
  1341. bool ServerMap::isBlockInQueue(v3s16 pos)
  1342. {
  1343. return m_emerge && m_emerge->isBlockInQueue(pos);
  1344. }
  1345. void ServerMap::addNodeAndUpdate(v3s16 p, MapNode n,
  1346. std::map<v3s16, MapBlock*> &modified_blocks,
  1347. bool remove_metadata)
  1348. {
  1349. Map::addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
  1350. /*
  1351. Add neighboring liquid nodes and this node to transform queue.
  1352. (it's vital for the node itself to get updated last, if it was removed.)
  1353. */
  1354. for (const v3s16 &dir : g_7dirs) {
  1355. v3s16 p2 = p + dir;
  1356. bool is_valid_position;
  1357. MapNode n2 = getNode(p2, &is_valid_position);
  1358. if(is_valid_position &&
  1359. (m_nodedef->get(n2).isLiquid() ||
  1360. n2.getContent() == CONTENT_AIR))
  1361. m_transforming_liquid.push_back(p2);
  1362. }
  1363. }
  1364. // N.B. This requires no synchronization, since data will not be modified unless
  1365. // the VoxelManipulator being updated belongs to the same thread.
  1366. void ServerMap::updateVManip(v3s16 pos)
  1367. {
  1368. Mapgen *mg = m_emerge->getCurrentMapgen();
  1369. if (!mg)
  1370. return;
  1371. MMVManip *vm = mg->vm;
  1372. if (!vm)
  1373. return;
  1374. if (!vm->m_area.contains(pos))
  1375. return;
  1376. s32 idx = vm->m_area.index(pos);
  1377. vm->m_data[idx] = getNode(pos);
  1378. vm->m_flags[idx] &= ~VOXELFLAG_NO_DATA;
  1379. vm->m_is_dirty = true;
  1380. }
  1381. void ServerMap::reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks)
  1382. {
  1383. m_loaded_blocks_gauge->set(all_blocks);
  1384. m_save_time_counter->increment(save_time_us);
  1385. m_save_count_counter->increment(saved_blocks);
  1386. }
  1387. void ServerMap::save(ModifiedState save_level)
  1388. {
  1389. if (!m_map_saving_enabled) {
  1390. warningstream<<"Not saving map, saving disabled."<<std::endl;
  1391. return;
  1392. }
  1393. const auto start_time = porting::getTimeUs();
  1394. if(save_level == MOD_STATE_CLEAN)
  1395. infostream<<"ServerMap: Saving whole map, this can take time."
  1396. <<std::endl;
  1397. if (m_map_metadata_changed || save_level == MOD_STATE_CLEAN) {
  1398. if (settings_mgr.saveMapMeta())
  1399. m_map_metadata_changed = false;
  1400. }
  1401. // Profile modified reasons
  1402. Profiler modprofiler;
  1403. u32 block_count = 0;
  1404. u32 block_count_all = 0; // Number of blocks in memory
  1405. // Don't do anything with sqlite unless something is really saved
  1406. bool save_started = false;
  1407. for (auto &sector_it : m_sectors) {
  1408. MapSector *sector = sector_it.second;
  1409. MapBlockVect blocks;
  1410. sector->getBlocks(blocks);
  1411. for (MapBlock *block : blocks) {
  1412. block_count_all++;
  1413. if(block->getModified() >= (u32)save_level) {
  1414. // Lazy beginSave()
  1415. if(!save_started) {
  1416. beginSave();
  1417. save_started = true;
  1418. }
  1419. modprofiler.add(block->getModifiedReasonString(), 1);
  1420. saveBlock(block);
  1421. block_count++;
  1422. }
  1423. }
  1424. }
  1425. if(save_started)
  1426. endSave();
  1427. /*
  1428. Only print if something happened or saved whole map
  1429. */
  1430. if(save_level == MOD_STATE_CLEAN
  1431. || block_count != 0) {
  1432. infostream << "ServerMap: Written: "
  1433. << block_count << " blocks"
  1434. << ", " << block_count_all << " blocks in memory."
  1435. << std::endl;
  1436. PrintInfo(infostream); // ServerMap/ClientMap:
  1437. infostream<<"Blocks modified by: "<<std::endl;
  1438. modprofiler.print(infostream);
  1439. }
  1440. const auto end_time = porting::getTimeUs();
  1441. reportMetrics(end_time - start_time, block_count, block_count_all);
  1442. }
  1443. void ServerMap::listAllLoadableBlocks(std::vector<v3s16> &dst)
  1444. {
  1445. dbase->listAllLoadableBlocks(dst);
  1446. if (dbase_ro)
  1447. dbase_ro->listAllLoadableBlocks(dst);
  1448. }
  1449. void ServerMap::listAllLoadedBlocks(std::vector<v3s16> &dst)
  1450. {
  1451. for (auto &sector_it : m_sectors) {
  1452. MapSector *sector = sector_it.second;
  1453. MapBlockVect blocks;
  1454. sector->getBlocks(blocks);
  1455. for (MapBlock *block : blocks) {
  1456. v3s16 p = block->getPos();
  1457. dst.push_back(p);
  1458. }
  1459. }
  1460. }
  1461. MapDatabase *ServerMap::createDatabase(
  1462. const std::string &name,
  1463. const std::string &savedir,
  1464. Settings &conf)
  1465. {
  1466. if (name == "sqlite3")
  1467. return new MapDatabaseSQLite3(savedir);
  1468. if (name == "dummy")
  1469. return new Database_Dummy();
  1470. #if USE_LEVELDB
  1471. if (name == "leveldb")
  1472. return new Database_LevelDB(savedir);
  1473. #endif
  1474. #if USE_REDIS
  1475. if (name == "redis")
  1476. return new Database_Redis(conf);
  1477. #endif
  1478. #if USE_POSTGRESQL
  1479. if (name == "postgresql") {
  1480. std::string connect_string;
  1481. conf.getNoEx("pgsql_connection", connect_string);
  1482. return new MapDatabasePostgreSQL(connect_string);
  1483. }
  1484. #endif
  1485. throw BaseException(std::string("Database backend ") + name + " not supported.");
  1486. }
  1487. void ServerMap::beginSave()
  1488. {
  1489. dbase->beginSave();
  1490. }
  1491. void ServerMap::endSave()
  1492. {
  1493. dbase->endSave();
  1494. }
  1495. bool ServerMap::saveBlock(MapBlock *block)
  1496. {
  1497. return saveBlock(block, dbase, m_map_compression_level);
  1498. }
  1499. bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db, int compression_level)
  1500. {
  1501. v3s16 p3d = block->getPos();
  1502. // Dummy blocks are not written
  1503. if (block->isDummy()) {
  1504. warningstream << "saveBlock: Not writing dummy block "
  1505. << PP(p3d) << std::endl;
  1506. return true;
  1507. }
  1508. // Format used for writing
  1509. u8 version = SER_FMT_VER_HIGHEST_WRITE;
  1510. /*
  1511. [0] u8 serialization version
  1512. [1] data
  1513. */
  1514. std::ostringstream o(std::ios_base::binary);
  1515. o.write((char*) &version, 1);
  1516. block->serialize(o, version, true, compression_level);
  1517. bool ret = db->saveBlock(p3d, o.str());
  1518. if (ret) {
  1519. // We just wrote it to the disk so clear modified flag
  1520. block->resetModified();
  1521. }
  1522. return ret;
  1523. }
  1524. void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load)
  1525. {
  1526. try {
  1527. std::istringstream is(*blob, std::ios_base::binary);
  1528. u8 version = SER_FMT_VER_INVALID;
  1529. is.read((char*)&version, 1);
  1530. if(is.fail())
  1531. throw SerializationError("ServerMap::loadBlock(): Failed"
  1532. " to read MapBlock version");
  1533. MapBlock *block = NULL;
  1534. bool created_new = false;
  1535. block = sector->getBlockNoCreateNoEx(p3d.Y);
  1536. if(block == NULL)
  1537. {
  1538. block = sector->createBlankBlockNoInsert(p3d.Y);
  1539. created_new = true;
  1540. }
  1541. // Read basic data
  1542. block->deSerialize(is, version, true);
  1543. // If it's a new block, insert it to the map
  1544. if (created_new) {
  1545. sector->insertBlock(block);
  1546. ReflowScan scanner(this, m_emerge->ndef);
  1547. scanner.scan(block, &m_transforming_liquid);
  1548. }
  1549. /*
  1550. Save blocks loaded in old format in new format
  1551. */
  1552. //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load)
  1553. // Only save if asked to; no need to update version
  1554. if(save_after_load)
  1555. saveBlock(block);
  1556. // We just loaded it from, so it's up-to-date.
  1557. block->resetModified();
  1558. }
  1559. catch(SerializationError &e)
  1560. {
  1561. errorstream<<"Invalid block data in database"
  1562. <<" ("<<p3d.X<<","<<p3d.Y<<","<<p3d.Z<<")"
  1563. <<" (SerializationError): "<<e.what()<<std::endl;
  1564. // TODO: Block should be marked as invalid in memory so that it is
  1565. // not touched but the game can run
  1566. if(g_settings->getBool("ignore_world_load_errors")){
  1567. errorstream<<"Ignoring block load error. Duck and cover! "
  1568. <<"(ignore_world_load_errors)"<<std::endl;
  1569. } else {
  1570. throw SerializationError("Invalid block data in database");
  1571. }
  1572. }
  1573. }
  1574. MapBlock* ServerMap::loadBlock(v3s16 blockpos)
  1575. {
  1576. bool created_new = (getBlockNoCreateNoEx(blockpos) == NULL);
  1577. v2s16 p2d(blockpos.X, blockpos.Z);
  1578. std::string ret;
  1579. dbase->loadBlock(blockpos, &ret);
  1580. if (!ret.empty()) {
  1581. loadBlock(&ret, blockpos, createSector(p2d), false);
  1582. } else if (dbase_ro) {
  1583. dbase_ro->loadBlock(blockpos, &ret);
  1584. if (!ret.empty()) {
  1585. loadBlock(&ret, blockpos, createSector(p2d), false);
  1586. }
  1587. } else {
  1588. return NULL;
  1589. }
  1590. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  1591. if (created_new && (block != NULL)) {
  1592. std::map<v3s16, MapBlock*> modified_blocks;
  1593. // Fix lighting if necessary
  1594. voxalgo::update_block_border_lighting(this, block, modified_blocks);
  1595. if (!modified_blocks.empty()) {
  1596. //Modified lighting, send event
  1597. MapEditEvent event;
  1598. event.type = MEET_OTHER;
  1599. std::map<v3s16, MapBlock *>::iterator it;
  1600. for (it = modified_blocks.begin();
  1601. it != modified_blocks.end(); ++it)
  1602. event.modified_blocks.insert(it->first);
  1603. dispatchEvent(event);
  1604. }
  1605. }
  1606. return block;
  1607. }
  1608. bool ServerMap::deleteBlock(v3s16 blockpos)
  1609. {
  1610. if (!dbase->deleteBlock(blockpos))
  1611. return false;
  1612. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  1613. if (block) {
  1614. v2s16 p2d(blockpos.X, blockpos.Z);
  1615. MapSector *sector = getSectorNoGenerate(p2d);
  1616. if (!sector)
  1617. return false;
  1618. sector->deleteBlock(block);
  1619. }
  1620. return true;
  1621. }
  1622. void ServerMap::PrintInfo(std::ostream &out)
  1623. {
  1624. out<<"ServerMap: ";
  1625. }
  1626. bool ServerMap::repairBlockLight(v3s16 blockpos,
  1627. std::map<v3s16, MapBlock *> *modified_blocks)
  1628. {
  1629. MapBlock *block = emergeBlock(blockpos, false);
  1630. if (!block || !block->isGenerated())
  1631. return false;
  1632. voxalgo::repair_block_light(this, block, modified_blocks);
  1633. return true;
  1634. }
  1635. MMVManip::MMVManip(Map *map):
  1636. VoxelManipulator(),
  1637. m_map(map)
  1638. {
  1639. assert(map);
  1640. }
  1641. void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
  1642. bool load_if_inexistent)
  1643. {
  1644. TimeTaker timer1("initialEmerge", &emerge_time);
  1645. assert(m_map);
  1646. // Units of these are MapBlocks
  1647. v3s16 p_min = blockpos_min;
  1648. v3s16 p_max = blockpos_max;
  1649. VoxelArea block_area_nodes
  1650. (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
  1651. u32 size_MB = block_area_nodes.getVolume()*4/1000000;
  1652. if(size_MB >= 1)
  1653. {
  1654. infostream<<"initialEmerge: area: ";
  1655. block_area_nodes.print(infostream);
  1656. infostream<<" ("<<size_MB<<"MB)";
  1657. infostream<<std::endl;
  1658. }
  1659. addArea(block_area_nodes);
  1660. for(s32 z=p_min.Z; z<=p_max.Z; z++)
  1661. for(s32 y=p_min.Y; y<=p_max.Y; y++)
  1662. for(s32 x=p_min.X; x<=p_max.X; x++)
  1663. {
  1664. u8 flags = 0;
  1665. MapBlock *block;
  1666. v3s16 p(x,y,z);
  1667. std::map<v3s16, u8>::iterator n;
  1668. n = m_loaded_blocks.find(p);
  1669. if(n != m_loaded_blocks.end())
  1670. continue;
  1671. bool block_data_inexistent = false;
  1672. {
  1673. TimeTaker timer2("emerge load", &emerge_load_time);
  1674. block = m_map->getBlockNoCreateNoEx(p);
  1675. if (!block || block->isDummy())
  1676. block_data_inexistent = true;
  1677. else
  1678. block->copyTo(*this);
  1679. }
  1680. if(block_data_inexistent)
  1681. {
  1682. if (load_if_inexistent && !blockpos_over_max_limit(p)) {
  1683. ServerMap *svrmap = (ServerMap *)m_map;
  1684. block = svrmap->emergeBlock(p, false);
  1685. if (block == NULL)
  1686. block = svrmap->createBlock(p);
  1687. block->copyTo(*this);
  1688. } else {
  1689. flags |= VMANIP_BLOCK_DATA_INEXIST;
  1690. /*
  1691. Mark area inexistent
  1692. */
  1693. VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
  1694. // Fill with VOXELFLAG_NO_DATA
  1695. for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++)
  1696. for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++)
  1697. {
  1698. s32 i = m_area.index(a.MinEdge.X,y,z);
  1699. memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE);
  1700. }
  1701. }
  1702. }
  1703. /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE)
  1704. {
  1705. // Mark that block was loaded as blank
  1706. flags |= VMANIP_BLOCK_CONTAINS_CIGNORE;
  1707. }*/
  1708. m_loaded_blocks[p] = flags;
  1709. }
  1710. m_is_dirty = false;
  1711. }
  1712. void MMVManip::blitBackAll(std::map<v3s16, MapBlock*> *modified_blocks,
  1713. bool overwrite_generated)
  1714. {
  1715. if(m_area.getExtent() == v3s16(0,0,0))
  1716. return;
  1717. assert(m_map);
  1718. /*
  1719. Copy data of all blocks
  1720. */
  1721. for (auto &loaded_block : m_loaded_blocks) {
  1722. v3s16 p = loaded_block.first;
  1723. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1724. bool existed = !(loaded_block.second & VMANIP_BLOCK_DATA_INEXIST);
  1725. if (!existed || (block == NULL) ||
  1726. (!overwrite_generated && block->isGenerated()))
  1727. continue;
  1728. block->copyFrom(*this);
  1729. block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_VMANIP);
  1730. if(modified_blocks)
  1731. (*modified_blocks)[p] = block;
  1732. }
  1733. }
  1734. MMVManip *MMVManip::clone() const
  1735. {
  1736. MMVManip *ret = new MMVManip();
  1737. const s32 size = m_area.getVolume();
  1738. ret->m_area = m_area;
  1739. if (m_data) {
  1740. ret->m_data = new MapNode[size];
  1741. memcpy(ret->m_data, m_data, size * sizeof(MapNode));
  1742. }
  1743. if (m_flags) {
  1744. ret->m_flags = new u8[size];
  1745. memcpy(ret->m_flags, m_flags, size * sizeof(u8));
  1746. }
  1747. ret->m_is_dirty = m_is_dirty;
  1748. // Even if the copy is disconnected from a map object keep the information
  1749. // needed to write it back to one
  1750. ret->m_loaded_blocks = m_loaded_blocks;
  1751. return ret;
  1752. }
  1753. void MMVManip::reparent(Map *map)
  1754. {
  1755. assert(map && !m_map);
  1756. m_map = map;
  1757. }
  1758. //END