map.cpp 58 KB

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