mapgen.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
  5. Copyright (C) 2015-2018 paramat
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU Lesser General Public License as published by
  8. the Free Software Foundation; either version 2.1 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public License along
  15. with this program; if not, write to the Free Software Foundation, Inc.,
  16. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. */
  18. #include <cmath>
  19. #include "mapgen.h"
  20. #include "voxel.h"
  21. #include "noise.h"
  22. #include "gamedef.h"
  23. #include "mg_biome.h"
  24. #include "mapblock.h"
  25. #include "mapnode.h"
  26. #include "map.h"
  27. #include "nodedef.h"
  28. #include "emerge.h"
  29. #include "voxelalgorithms.h"
  30. #include "porting.h"
  31. #include "profiler.h"
  32. #include "settings.h"
  33. #include "treegen.h"
  34. #include "serialization.h"
  35. #include "util/serialize.h"
  36. #include "util/numeric.h"
  37. #include "util/directiontables.h"
  38. #include "filesys.h"
  39. #include "log.h"
  40. #include "mapgen_carpathian.h"
  41. #include "mapgen_flat.h"
  42. #include "mapgen_fractal.h"
  43. #include "mapgen_v5.h"
  44. #include "mapgen_v6.h"
  45. #include "mapgen_v7.h"
  46. #include "mapgen_valleys.h"
  47. #include "mapgen_singlenode.h"
  48. #include "cavegen.h"
  49. #include "dungeongen.h"
  50. FlagDesc flagdesc_mapgen[] = {
  51. {"caves", MG_CAVES},
  52. {"dungeons", MG_DUNGEONS},
  53. {"light", MG_LIGHT},
  54. {"decorations", MG_DECORATIONS},
  55. {"biomes", MG_BIOMES},
  56. {"ores", MG_ORES},
  57. {NULL, 0}
  58. };
  59. FlagDesc flagdesc_gennotify[] = {
  60. {"dungeon", 1 << GENNOTIFY_DUNGEON},
  61. {"temple", 1 << GENNOTIFY_TEMPLE},
  62. {"cave_begin", 1 << GENNOTIFY_CAVE_BEGIN},
  63. {"cave_end", 1 << GENNOTIFY_CAVE_END},
  64. {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN},
  65. {"large_cave_end", 1 << GENNOTIFY_LARGECAVE_END},
  66. {"decoration", 1 << GENNOTIFY_DECORATION},
  67. {"custom", 1 << GENNOTIFY_CUSTOM},
  68. {NULL, 0}
  69. };
  70. struct MapgenDesc {
  71. const char *name;
  72. bool is_user_visible;
  73. };
  74. ////
  75. //// Built-in mapgens
  76. ////
  77. // Order used here defines the order of appearance in mainmenu.
  78. // v6 always last to discourage selection.
  79. // Special mapgens flat, fractal, singlenode, next to last. Of these, singlenode
  80. // last to discourage selection.
  81. // Of the remaining, v5 last due to age, v7 first due to being the default.
  82. // The order of 'enum MapgenType' in mapgen.h must match this order.
  83. static MapgenDesc g_reg_mapgens[] = {
  84. {"v7", true},
  85. {"valleys", true},
  86. {"carpathian", true},
  87. {"v5", true},
  88. {"flat", true},
  89. {"fractal", true},
  90. {"singlenode", true},
  91. {"v6", true},
  92. };
  93. static_assert(
  94. ARRLEN(g_reg_mapgens) == MAPGEN_INVALID,
  95. "g_reg_mapgens is wrong size");
  96. ////
  97. //// Mapgen
  98. ////
  99. Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeParams *emerge) :
  100. gennotify(emerge->createNotifier())
  101. {
  102. id = mapgenid;
  103. water_level = params->water_level;
  104. mapgen_limit = params->mapgen_limit;
  105. flags = params->flags;
  106. csize = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE);
  107. /*
  108. We are losing half our entropy by doing this, but it is necessary to
  109. preserve reverse compatibility. If the top half of our current 64 bit
  110. seeds ever starts getting used, existing worlds will break due to a
  111. different hash outcome and no way to differentiate between versions.
  112. A solution could be to add a new bit to designate that the top half of
  113. the seed value should be used, essentially a 1-bit version code, but
  114. this would require increasing the total size of a seed to 9 bytes (yuck)
  115. It's probably okay if this never gets fixed. 4.2 billion possibilities
  116. ought to be enough for anyone.
  117. */
  118. seed = (s32)params->seed;
  119. m_emerge = emerge;
  120. ndef = emerge->ndef;
  121. }
  122. Mapgen::~Mapgen()
  123. {
  124. delete m_emerge; // this is our responsibility
  125. }
  126. MapgenType Mapgen::getMapgenType(const std::string &mgname)
  127. {
  128. for (size_t i = 0; i != ARRLEN(g_reg_mapgens); i++) {
  129. if (mgname == g_reg_mapgens[i].name)
  130. return (MapgenType)i;
  131. }
  132. return MAPGEN_INVALID;
  133. }
  134. const char *Mapgen::getMapgenName(MapgenType mgtype)
  135. {
  136. size_t index = (size_t)mgtype;
  137. if (index == MAPGEN_INVALID || index >= ARRLEN(g_reg_mapgens))
  138. return "invalid";
  139. return g_reg_mapgens[index].name;
  140. }
  141. Mapgen *Mapgen::createMapgen(MapgenType mgtype, MapgenParams *params,
  142. EmergeParams *emerge)
  143. {
  144. switch (mgtype) {
  145. case MAPGEN_CARPATHIAN:
  146. return new MapgenCarpathian((MapgenCarpathianParams *)params, emerge);
  147. case MAPGEN_FLAT:
  148. return new MapgenFlat((MapgenFlatParams *)params, emerge);
  149. case MAPGEN_FRACTAL:
  150. return new MapgenFractal((MapgenFractalParams *)params, emerge);
  151. case MAPGEN_SINGLENODE:
  152. return new MapgenSinglenode((MapgenSinglenodeParams *)params, emerge);
  153. case MAPGEN_V5:
  154. return new MapgenV5((MapgenV5Params *)params, emerge);
  155. case MAPGEN_V6:
  156. return new MapgenV6((MapgenV6Params *)params, emerge);
  157. case MAPGEN_V7:
  158. return new MapgenV7((MapgenV7Params *)params, emerge);
  159. case MAPGEN_VALLEYS:
  160. return new MapgenValleys((MapgenValleysParams *)params, emerge);
  161. default:
  162. return nullptr;
  163. }
  164. }
  165. MapgenParams *Mapgen::createMapgenParams(MapgenType mgtype)
  166. {
  167. switch (mgtype) {
  168. case MAPGEN_CARPATHIAN:
  169. return new MapgenCarpathianParams;
  170. case MAPGEN_FLAT:
  171. return new MapgenFlatParams;
  172. case MAPGEN_FRACTAL:
  173. return new MapgenFractalParams;
  174. case MAPGEN_SINGLENODE:
  175. return new MapgenSinglenodeParams;
  176. case MAPGEN_V5:
  177. return new MapgenV5Params;
  178. case MAPGEN_V6:
  179. return new MapgenV6Params;
  180. case MAPGEN_V7:
  181. return new MapgenV7Params;
  182. case MAPGEN_VALLEYS:
  183. return new MapgenValleysParams;
  184. default:
  185. return nullptr;
  186. }
  187. }
  188. void Mapgen::getMapgenNames(std::vector<const char *> *mgnames, bool include_hidden)
  189. {
  190. for (u32 i = 0; i != ARRLEN(g_reg_mapgens); i++) {
  191. if (include_hidden || g_reg_mapgens[i].is_user_visible)
  192. mgnames->push_back(g_reg_mapgens[i].name);
  193. }
  194. }
  195. void Mapgen::setDefaultSettings(Settings *settings)
  196. {
  197. settings->setDefault("mg_flags", flagdesc_mapgen,
  198. MG_CAVES | MG_DUNGEONS | MG_LIGHT | MG_DECORATIONS | MG_BIOMES | MG_ORES);
  199. for (int i = 0; i < (int)MAPGEN_INVALID; ++i) {
  200. MapgenParams *params = createMapgenParams((MapgenType)i);
  201. params->setDefaultSettings(settings);
  202. delete params;
  203. }
  204. }
  205. u32 Mapgen::getBlockSeed(v3s16 p, s32 seed)
  206. {
  207. return (u32)seed +
  208. p.Z * 38134234 +
  209. p.Y * 42123 +
  210. p.X * 23;
  211. }
  212. u32 Mapgen::getBlockSeed2(v3s16 p, s32 seed)
  213. {
  214. // Multiply by unsigned number to avoid signed overflow (UB)
  215. u32 n = 1619U * p.X + 31337U * p.Y + 52591U * p.Z + 1013U * seed;
  216. n = (n >> 13) ^ n;
  217. return (n * (n * n * 60493 + 19990303) + 1376312589);
  218. }
  219. // Returns -MAX_MAP_GENERATION_LIMIT if not found
  220. s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax)
  221. {
  222. const v3s16 &em = vm->m_area.getExtent();
  223. u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
  224. s16 y;
  225. for (y = ymax; y >= ymin; y--) {
  226. MapNode &n = vm->m_data[i];
  227. if (ndef->get(n).walkable)
  228. break;
  229. VoxelArea::add_y(em, i, -1);
  230. }
  231. return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT;
  232. }
  233. // Returns -MAX_MAP_GENERATION_LIMIT if not found or if ground is found first
  234. s16 Mapgen::findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax)
  235. {
  236. const v3s16 &em = vm->m_area.getExtent();
  237. u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
  238. s16 y;
  239. for (y = ymax; y >= ymin; y--) {
  240. MapNode &n = vm->m_data[i];
  241. if (ndef->get(n).walkable)
  242. return -MAX_MAP_GENERATION_LIMIT;
  243. if (ndef->get(n).isLiquid())
  244. break;
  245. VoxelArea::add_y(em, i, -1);
  246. }
  247. return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT;
  248. }
  249. void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax)
  250. {
  251. if (!heightmap)
  252. return;
  253. //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
  254. int index = 0;
  255. for (s16 z = nmin.Z; z <= nmax.Z; z++) {
  256. for (s16 x = nmin.X; x <= nmax.X; x++, index++) {
  257. s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
  258. heightmap[index] = y;
  259. }
  260. }
  261. }
  262. void Mapgen::getSurfaces(v2s16 p2d, s16 ymin, s16 ymax,
  263. std::vector<s16> &floors, std::vector<s16> &ceilings)
  264. {
  265. const v3s16 &em = vm->m_area.getExtent();
  266. bool is_walkable = false;
  267. u32 vi = vm->m_area.index(p2d.X, ymax, p2d.Y);
  268. MapNode mn_max = vm->m_data[vi];
  269. bool walkable_above = ndef->get(mn_max).walkable;
  270. VoxelArea::add_y(em, vi, -1);
  271. for (s16 y = ymax - 1; y >= ymin; y--) {
  272. MapNode mn = vm->m_data[vi];
  273. is_walkable = ndef->get(mn).walkable;
  274. if (is_walkable && !walkable_above) {
  275. floors.push_back(y);
  276. } else if (!is_walkable && walkable_above) {
  277. ceilings.push_back(y + 1);
  278. }
  279. VoxelArea::add_y(em, vi, -1);
  280. walkable_above = is_walkable;
  281. }
  282. }
  283. inline bool Mapgen::isLiquidHorizontallyFlowable(u32 vi, v3s16 em)
  284. {
  285. u32 vi_neg_x = vi;
  286. VoxelArea::add_x(em, vi_neg_x, -1);
  287. if (vm->m_data[vi_neg_x].getContent() != CONTENT_IGNORE) {
  288. const ContentFeatures &c_nx = ndef->get(vm->m_data[vi_neg_x]);
  289. if (c_nx.floodable && !c_nx.isLiquid())
  290. return true;
  291. }
  292. u32 vi_pos_x = vi;
  293. VoxelArea::add_x(em, vi_pos_x, +1);
  294. if (vm->m_data[vi_pos_x].getContent() != CONTENT_IGNORE) {
  295. const ContentFeatures &c_px = ndef->get(vm->m_data[vi_pos_x]);
  296. if (c_px.floodable && !c_px.isLiquid())
  297. return true;
  298. }
  299. u32 vi_neg_z = vi;
  300. VoxelArea::add_z(em, vi_neg_z, -1);
  301. if (vm->m_data[vi_neg_z].getContent() != CONTENT_IGNORE) {
  302. const ContentFeatures &c_nz = ndef->get(vm->m_data[vi_neg_z]);
  303. if (c_nz.floodable && !c_nz.isLiquid())
  304. return true;
  305. }
  306. u32 vi_pos_z = vi;
  307. VoxelArea::add_z(em, vi_pos_z, +1);
  308. if (vm->m_data[vi_pos_z].getContent() != CONTENT_IGNORE) {
  309. const ContentFeatures &c_pz = ndef->get(vm->m_data[vi_pos_z]);
  310. if (c_pz.floodable && !c_pz.isLiquid())
  311. return true;
  312. }
  313. return false;
  314. }
  315. void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax)
  316. {
  317. bool isignored, isliquid, wasignored, wasliquid, waschecked, waspushed;
  318. content_t was_n;
  319. const v3s16 &em = vm->m_area.getExtent();
  320. isignored = true;
  321. isliquid = false;
  322. was_n = CONTENT_IGNORE;
  323. for (s16 z = nmin.Z + 1; z <= nmax.Z - 1; z++)
  324. for (s16 x = nmin.X + 1; x <= nmax.X - 1; x++) {
  325. wasignored = true;
  326. wasliquid = false;
  327. waschecked = false;
  328. waspushed = false;
  329. u32 vi = vm->m_area.index(x, nmax.Y, z);
  330. for (s16 y = nmax.Y; y >= nmin.Y; y--) {
  331. const content_t is_n = vm->m_data[vi].getContent();
  332. if (is_n != was_n) {
  333. isignored = is_n == CONTENT_IGNORE;
  334. isliquid = ndef->get(is_n).isLiquid();
  335. }
  336. if (isignored || wasignored || isliquid == wasliquid) {
  337. // Neither topmost node of liquid column nor topmost node below column
  338. waschecked = false;
  339. waspushed = false;
  340. } else if (isliquid) {
  341. // This is the topmost node in the column
  342. bool ispushed = false;
  343. if (isLiquidHorizontallyFlowable(vi, em)) {
  344. trans_liquid->push_back(v3s16(x, y, z));
  345. ispushed = true;
  346. }
  347. // Remember waschecked and waspushed to avoid repeated
  348. // checks/pushes in case the column consists of only this node
  349. waschecked = true;
  350. waspushed = ispushed;
  351. } else {
  352. // This is the topmost node below a liquid column
  353. u32 vi_above = vi;
  354. VoxelArea::add_y(em, vi_above, 1);
  355. if (!waspushed && (ndef->get(vm->m_data[vi]).floodable ||
  356. (!waschecked && isLiquidHorizontallyFlowable(vi_above, em)))) {
  357. // Push back the lowest node in the column which is one
  358. // node above this one
  359. trans_liquid->push_back(v3s16(x, y + 1, z));
  360. }
  361. }
  362. was_n = is_n;
  363. wasliquid = isliquid;
  364. wasignored = isignored;
  365. VoxelArea::add_y(em, vi, -1);
  366. }
  367. }
  368. }
  369. void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax)
  370. {
  371. ScopeProfiler sp(g_profiler, "EmergeThread: update lighting", SPT_AVG);
  372. VoxelArea a(nmin, nmax);
  373. for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
  374. for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
  375. u32 i = vm->m_area.index(a.MinEdge.X, y, z);
  376. for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
  377. vm->m_data[i].param1 = light;
  378. }
  379. }
  380. }
  381. void Mapgen::lightSpread(VoxelArea &a, std::queue<std::pair<v3s16, u8>> &queue,
  382. const v3s16 &p, u8 light)
  383. {
  384. if (light <= 1 || !a.contains(p))
  385. return;
  386. u32 vi = vm->m_area.index(p);
  387. MapNode &n = vm->m_data[vi];
  388. // Decay light in each of the banks separately
  389. u8 light_day = light & 0x0F;
  390. if (light_day > 0)
  391. light_day -= 0x01;
  392. u8 light_night = light & 0xF0;
  393. if (light_night > 0)
  394. light_night -= 0x10;
  395. // Bail out only if we have no more light from either bank to propogate, or
  396. // we hit a solid block that light cannot pass through.
  397. if ((light_day <= (n.param1 & 0x0F) &&
  398. light_night <= (n.param1 & 0xF0)) ||
  399. !ndef->getLightingFlags(n).light_propagates)
  400. return;
  401. // MYMAX still needed here because we only exit early if both banks have
  402. // nothing to propagate anymore.
  403. light = MYMAX(light_day, n.param1 & 0x0F) |
  404. MYMAX(light_night, n.param1 & 0xF0);
  405. n.param1 = light;
  406. // add to queue
  407. queue.emplace(p, light);
  408. }
  409. void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax,
  410. bool propagate_shadow)
  411. {
  412. ScopeProfiler sp(g_profiler, "EmergeThread: update lighting", SPT_AVG);
  413. propagateSunlight(nmin, nmax, propagate_shadow);
  414. spreadLight(full_nmin, full_nmax);
  415. }
  416. void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow)
  417. {
  418. //TimeTaker t("propagateSunlight");
  419. VoxelArea a(nmin, nmax);
  420. bool block_is_underground = (water_level >= nmax.Y);
  421. const v3s16 &em = vm->m_area.getExtent();
  422. // NOTE: Direct access to the low 4 bits of param1 is okay here because,
  423. // by definition, sunlight will never be in the night lightbank.
  424. for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
  425. for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
  426. // see if we can get a light value from the overtop
  427. u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
  428. if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
  429. if (block_is_underground)
  430. continue;
  431. } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN &&
  432. propagate_shadow) {
  433. continue;
  434. }
  435. VoxelArea::add_y(em, i, -1);
  436. for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
  437. MapNode &n = vm->m_data[i];
  438. if (!ndef->getLightingFlags(n).sunlight_propagates)
  439. break;
  440. n.param1 = LIGHT_SUN;
  441. VoxelArea::add_y(em, i, -1);
  442. }
  443. }
  444. }
  445. //printf("propagateSunlight: %dms\n", t.stop());
  446. }
  447. void Mapgen::spreadLight(const v3s16 &nmin, const v3s16 &nmax)
  448. {
  449. //TimeTaker t("spreadLight");
  450. std::queue<std::pair<v3s16, u8>> queue;
  451. VoxelArea a(nmin, nmax);
  452. for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
  453. for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
  454. u32 i = vm->m_area.index(a.MinEdge.X, y, z);
  455. for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
  456. MapNode &n = vm->m_data[i];
  457. if (n.getContent() == CONTENT_IGNORE)
  458. continue;
  459. ContentLightingFlags cf = ndef->getLightingFlags(n);
  460. if (!cf.light_propagates)
  461. continue;
  462. // TODO(hmmmmm): Abstract away direct param1 accesses with a
  463. // wrapper, but something lighter than MapNode::get/setLight
  464. u8 light_produced = cf.light_source;
  465. if (light_produced)
  466. n.param1 = light_produced | (light_produced << 4);
  467. u8 light = n.param1;
  468. if (light) {
  469. const v3s16 p(x, y, z);
  470. // spread to all 6 neighbor nodes
  471. for (const auto &dir : g_6dirs)
  472. lightSpread(a, queue, p + dir, light);
  473. }
  474. }
  475. }
  476. }
  477. while (!queue.empty()) {
  478. const auto &i = queue.front();
  479. // spread to all 6 neighbor nodes
  480. for (const auto &dir : g_6dirs)
  481. lightSpread(a, queue, i.first + dir, i.second);
  482. queue.pop();
  483. }
  484. //printf("spreadLight: %lums\n", t.stop());
  485. }
  486. ////
  487. //// MapgenBasic
  488. ////
  489. MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerge)
  490. : Mapgen(mapgenid, params, emerge)
  491. {
  492. this->m_bmgr = emerge->biomemgr;
  493. //// Here, 'stride' refers to the number of elements needed to skip to index
  494. //// an adjacent element for that coordinate in noise/height/biome maps
  495. //// (*not* vmanip content map!)
  496. // Note there is no X stride explicitly defined. Items adjacent in the X
  497. // coordinate are assumed to be adjacent in memory as well (i.e. stride of 1).
  498. // Number of elements to skip to get to the next Y coordinate
  499. this->ystride = csize.X;
  500. // Number of elements to skip to get to the next Z coordinate
  501. this->zstride = csize.X * csize.Y;
  502. // Z-stride value for maps oversized for 1-down overgeneration
  503. this->zstride_1d = csize.X * (csize.Y + 1);
  504. // Z-stride value for maps oversized for 1-up 1-down overgeneration
  505. this->zstride_1u1d = csize.X * (csize.Y + 2);
  506. //// Allocate heightmap
  507. this->heightmap = new s16[csize.X * csize.Z];
  508. //// Initialize biome generator
  509. biomegen = emerge->biomegen;
  510. biomegen->assertChunkSize(csize);
  511. biomemap = biomegen->biomemap;
  512. //// Look up some commonly used content
  513. c_stone = ndef->getId("mapgen_stone");
  514. c_water_source = ndef->getId("mapgen_water_source");
  515. c_river_water_source = ndef->getId("mapgen_river_water_source");
  516. c_lava_source = ndef->getId("mapgen_lava_source");
  517. c_cobble = ndef->getId("mapgen_cobble");
  518. // Fall back to more basic content if not defined.
  519. // Lava falls back to water as both are suitable as cave liquids.
  520. if (c_lava_source == CONTENT_IGNORE)
  521. c_lava_source = c_water_source;
  522. if (c_stone == CONTENT_IGNORE)
  523. errorstream << "Mapgen: Mapgen alias 'mapgen_stone' is invalid!" << std::endl;
  524. if (c_water_source == CONTENT_IGNORE)
  525. errorstream << "Mapgen: Mapgen alias 'mapgen_water_source' is invalid!" << std::endl;
  526. if (c_river_water_source == CONTENT_IGNORE)
  527. warningstream << "Mapgen: Mapgen alias 'mapgen_river_water_source' is invalid!" << std::endl;
  528. }
  529. MapgenBasic::~MapgenBasic()
  530. {
  531. delete []heightmap;
  532. }
  533. void MapgenBasic::generateBiomes()
  534. {
  535. // can't generate biomes without a biome generator!
  536. assert(biomegen);
  537. assert(biomemap);
  538. const v3s16 &em = vm->m_area.getExtent();
  539. u32 index = 0;
  540. noise_filler_depth->perlinMap2D(node_min.X, node_min.Z);
  541. s16 *biome_transitions = biomegen->getBiomeTransitions();
  542. for (s16 z = node_min.Z; z <= node_max.Z; z++)
  543. for (s16 x = node_min.X; x <= node_max.X; x++, index++) {
  544. Biome *biome = NULL;
  545. biome_t water_biome_index = 0;
  546. u16 depth_top = 0;
  547. u16 base_filler = 0;
  548. u16 depth_water_top = 0;
  549. u16 depth_riverbed = 0;
  550. u32 vi = vm->m_area.index(x, node_max.Y, z);
  551. int cur_biome_depth = 0;
  552. s16 biome_y_min = biome_transitions[cur_biome_depth];
  553. // Check node at base of mapchunk above, either a node of a previously
  554. // generated mapchunk or if not, a node of overgenerated base terrain.
  555. content_t c_above = vm->m_data[vi + em.X].getContent();
  556. bool air_above = c_above == CONTENT_AIR;
  557. bool river_water_above = c_above == c_river_water_source;
  558. bool water_above = c_above == c_water_source || river_water_above;
  559. biomemap[index] = BIOME_NONE;
  560. // If there is air or water above enable top/filler placement, otherwise force
  561. // nplaced to stone level by setting a number exceeding any possible filler depth.
  562. u16 nplaced = (air_above || water_above) ? 0 : U16_MAX;
  563. for (s16 y = node_max.Y; y >= node_min.Y; y--) {
  564. content_t c = vm->m_data[vi].getContent();
  565. // Biome is (re)calculated:
  566. // 1. At the surface of stone below air or water.
  567. // 2. At the surface of water below air.
  568. // 3. When stone or water is detected but biome has not yet been calculated.
  569. // 4. When stone or water is detected just below a biome's lower limit.
  570. bool is_stone_surface = (c == c_stone) &&
  571. (air_above || water_above || !biome || y < biome_y_min); // 1, 3, 4
  572. bool is_water_surface =
  573. (c == c_water_source || c == c_river_water_source) &&
  574. (air_above || !biome || y < biome_y_min); // 2, 3, 4
  575. if (is_stone_surface || is_water_surface) {
  576. if (!biome || y < biome_y_min) {
  577. // (Re)calculate biome
  578. biome = biomegen->getBiomeAtIndex(index, v3s16(x, y, z));
  579. // Finding the height of the next biome
  580. // On first iteration this may loop a couple times after than it should just run once
  581. while (y < biome_y_min) {
  582. biome_y_min = biome_transitions[++cur_biome_depth];
  583. }
  584. /*if (x == node_min.X && z == node_min.Z)
  585. printf("Map: check @ %i -> %s -> again at %i\n", y, biome->name.c_str(), biome_y_min);*/
  586. }
  587. // Add biome to biomemap at first stone surface detected
  588. if (biomemap[index] == BIOME_NONE && is_stone_surface)
  589. biomemap[index] = biome->index;
  590. // Store biome of first water surface detected, as a fallback
  591. // entry for the biomemap.
  592. if (water_biome_index == 0 && is_water_surface)
  593. water_biome_index = biome->index;
  594. depth_top = biome->depth_top;
  595. base_filler = MYMAX(depth_top +
  596. biome->depth_filler +
  597. noise_filler_depth->result[index], 0.0f);
  598. depth_water_top = biome->depth_water_top;
  599. depth_riverbed = biome->depth_riverbed;
  600. }
  601. if (c == c_stone) {
  602. content_t c_below = vm->m_data[vi - em.X].getContent();
  603. // If the node below isn't solid, make this node stone, so that
  604. // any top/filler nodes above are structurally supported.
  605. // This is done by aborting the cycle of top/filler placement
  606. // immediately by forcing nplaced to stone level.
  607. if (c_below == CONTENT_AIR
  608. || c_below == c_water_source
  609. || c_below == c_river_water_source)
  610. nplaced = U16_MAX;
  611. if (river_water_above) {
  612. if (nplaced < depth_riverbed) {
  613. vm->m_data[vi] = MapNode(biome->c_riverbed);
  614. nplaced++;
  615. } else {
  616. nplaced = U16_MAX; // Disable top/filler placement
  617. river_water_above = false;
  618. }
  619. } else if (nplaced < depth_top) {
  620. vm->m_data[vi] = MapNode(biome->c_top);
  621. nplaced++;
  622. } else if (nplaced < base_filler) {
  623. vm->m_data[vi] = MapNode(biome->c_filler);
  624. nplaced++;
  625. } else {
  626. vm->m_data[vi] = MapNode(biome->c_stone);
  627. nplaced = U16_MAX; // Disable top/filler placement
  628. }
  629. air_above = false;
  630. water_above = false;
  631. } else if (c == c_water_source) {
  632. vm->m_data[vi] = MapNode((y > (s32)(water_level - depth_water_top))
  633. ? biome->c_water_top : biome->c_water);
  634. nplaced = 0; // Enable top/filler placement for next surface
  635. air_above = false;
  636. water_above = true;
  637. } else if (c == c_river_water_source) {
  638. vm->m_data[vi] = MapNode(biome->c_river_water);
  639. nplaced = 0; // Enable riverbed placement for next surface
  640. air_above = false;
  641. water_above = true;
  642. river_water_above = true;
  643. } else if (c == CONTENT_AIR) {
  644. nplaced = 0; // Enable top/filler placement for next surface
  645. air_above = true;
  646. water_above = false;
  647. } else { // Possible various nodes overgenerated from neighboring mapchunks
  648. nplaced = U16_MAX; // Disable top/filler placement
  649. air_above = false;
  650. water_above = false;
  651. }
  652. VoxelArea::add_y(em, vi, -1);
  653. }
  654. // If no stone surface detected in mapchunk column and a water surface
  655. // biome fallback exists, add it to the biomemap. This avoids water
  656. // surface decorations failing in deep water.
  657. if (biomemap[index] == BIOME_NONE && water_biome_index != 0)
  658. biomemap[index] = water_biome_index;
  659. }
  660. }
  661. void MapgenBasic::dustTopNodes()
  662. {
  663. if (node_max.Y < water_level)
  664. return;
  665. const v3s16 &em = vm->m_area.getExtent();
  666. u32 index = 0;
  667. for (s16 z = node_min.Z; z <= node_max.Z; z++)
  668. for (s16 x = node_min.X; x <= node_max.X; x++, index++) {
  669. Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index]);
  670. if (biome->c_dust == CONTENT_IGNORE)
  671. continue;
  672. // Check if mapchunk above has generated, if so, drop dust from 16 nodes
  673. // above current mapchunk top, above decorations that will extend above
  674. // the current mapchunk. If the mapchunk above has not generated, it
  675. // will provide this required dust when it does.
  676. u32 vi = vm->m_area.index(x, full_node_max.Y, z);
  677. content_t c_full_max = vm->m_data[vi].getContent();
  678. s16 y_start;
  679. if (c_full_max == CONTENT_AIR) {
  680. y_start = full_node_max.Y - 1;
  681. } else if (c_full_max == CONTENT_IGNORE) {
  682. vi = vm->m_area.index(x, node_max.Y + 1, z);
  683. content_t c_max = vm->m_data[vi].getContent();
  684. if (c_max == CONTENT_AIR)
  685. y_start = node_max.Y;
  686. else
  687. continue;
  688. } else {
  689. continue;
  690. }
  691. vi = vm->m_area.index(x, y_start, z);
  692. for (s16 y = y_start; y >= node_min.Y - 1; y--) {
  693. if (vm->m_data[vi].getContent() != CONTENT_AIR)
  694. break;
  695. VoxelArea::add_y(em, vi, -1);
  696. }
  697. content_t c = vm->m_data[vi].getContent();
  698. NodeDrawType dtype = ndef->get(c).drawtype;
  699. // Only place on cubic, walkable, non-dust nodes.
  700. // Dust check needed due to avoid double layer of dust caused by
  701. // dropping dust from 16 nodes above mapchunk top.
  702. if ((dtype == NDT_NORMAL ||
  703. dtype == NDT_ALLFACES ||
  704. dtype == NDT_ALLFACES_OPTIONAL ||
  705. dtype == NDT_GLASSLIKE ||
  706. dtype == NDT_GLASSLIKE_FRAMED ||
  707. dtype == NDT_GLASSLIKE_FRAMED_OPTIONAL) &&
  708. ndef->get(c).walkable && c != biome->c_dust) {
  709. VoxelArea::add_y(em, vi, 1);
  710. vm->m_data[vi] = MapNode(biome->c_dust);
  711. }
  712. }
  713. }
  714. void MapgenBasic::generateCavesNoiseIntersection(s16 max_stone_y)
  715. {
  716. // cave_width >= 10 is used to disable generation and avoid the intensive
  717. // 3D noise calculations. Tunnels already have zero width when cave_width > 1.
  718. if (node_min.Y > max_stone_y || cave_width >= 10.0f)
  719. return;
  720. CavesNoiseIntersection caves_noise(ndef, m_bmgr, biomegen, csize,
  721. &np_cave1, &np_cave2, seed, cave_width);
  722. caves_noise.generateCaves(vm, node_min, node_max, biomemap);
  723. }
  724. void MapgenBasic::generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_ymax)
  725. {
  726. if (node_min.Y > max_stone_y)
  727. return;
  728. PseudoRandom ps(blockseed + 21343);
  729. // Small randomwalk caves
  730. u32 num_small_caves = ps.range(small_cave_num_min, small_cave_num_max);
  731. for (u32 i = 0; i < num_small_caves; i++) {
  732. CavesRandomWalk cave(ndef, &gennotify, seed, water_level,
  733. c_water_source, c_lava_source, large_cave_flooded, biomegen);
  734. cave.makeCave(vm, node_min, node_max, &ps, false, max_stone_y, heightmap);
  735. }
  736. if (node_max.Y > large_cave_ymax)
  737. return;
  738. // Large randomwalk caves below 'large_cave_ymax'.
  739. // 'large_cave_ymax' can differ from the 'large_cave_depth' mapgen parameter,
  740. // it is set to world base to disable large caves in or near caverns.
  741. u32 num_large_caves = ps.range(large_cave_num_min, large_cave_num_max);
  742. for (u32 i = 0; i < num_large_caves; i++) {
  743. CavesRandomWalk cave(ndef, &gennotify, seed, water_level,
  744. c_water_source, c_lava_source, large_cave_flooded, biomegen);
  745. cave.makeCave(vm, node_min, node_max, &ps, true, max_stone_y, heightmap);
  746. }
  747. }
  748. bool MapgenBasic::generateCavernsNoise(s16 max_stone_y)
  749. {
  750. if (node_min.Y > max_stone_y || node_min.Y > cavern_limit)
  751. return false;
  752. CavernsNoise caverns_noise(ndef, csize, &np_cavern,
  753. seed, cavern_limit, cavern_taper, cavern_threshold);
  754. return caverns_noise.generateCaverns(vm, node_min, node_max);
  755. }
  756. void MapgenBasic::generateDungeons(s16 max_stone_y)
  757. {
  758. if (node_min.Y > max_stone_y || node_min.Y > dungeon_ymax ||
  759. node_max.Y < dungeon_ymin)
  760. return;
  761. u16 num_dungeons = std::fmax(std::floor(
  762. NoisePerlin3D(&np_dungeons, node_min.X, node_min.Y, node_min.Z, seed)), 0.0f);
  763. if (num_dungeons == 0)
  764. return;
  765. PseudoRandom ps(blockseed + 70033);
  766. DungeonParams dp;
  767. dp.np_alt_wall =
  768. NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0);
  769. dp.seed = seed;
  770. dp.only_in_ground = true;
  771. dp.num_dungeons = num_dungeons;
  772. dp.notifytype = GENNOTIFY_DUNGEON;
  773. dp.num_rooms = ps.range(2, 16);
  774. dp.room_size_min = v3s16(5, 5, 5);
  775. dp.room_size_max = v3s16(12, 6, 12);
  776. dp.room_size_large_min = v3s16(12, 6, 12);
  777. dp.room_size_large_max = v3s16(16, 16, 16);
  778. dp.large_room_chance = (ps.range(1, 4) == 1) ? 8 : 0;
  779. dp.diagonal_dirs = ps.range(1, 8) == 1;
  780. // Diagonal corridors must have 'hole' width >=2 to be passable
  781. u8 holewidth = (dp.diagonal_dirs) ? 2 : ps.range(1, 2);
  782. dp.holesize = v3s16(holewidth, 3, holewidth);
  783. dp.corridor_len_min = 1;
  784. dp.corridor_len_max = 13;
  785. // Get biome at mapchunk midpoint
  786. v3s16 chunk_mid = node_min + (node_max - node_min) / v3s16(2, 2, 2);
  787. Biome *biome = (Biome *)biomegen->getBiomeAtPoint(chunk_mid);
  788. // Use biome-defined dungeon nodes if defined
  789. if (biome->c_dungeon != CONTENT_IGNORE) {
  790. dp.c_wall = biome->c_dungeon;
  791. // If 'node_dungeon_alt' is not defined by biome, it and dp.c_alt_wall
  792. // become CONTENT_IGNORE which skips the alt wall node placement loop in
  793. // dungeongen.cpp.
  794. dp.c_alt_wall = biome->c_dungeon_alt;
  795. // Stairs fall back to 'c_dungeon' if not defined by biome
  796. dp.c_stair = (biome->c_dungeon_stair != CONTENT_IGNORE) ?
  797. biome->c_dungeon_stair : biome->c_dungeon;
  798. // Fallback to using cobble mapgen alias if defined
  799. } else if (c_cobble != CONTENT_IGNORE) {
  800. dp.c_wall = c_cobble;
  801. dp.c_alt_wall = CONTENT_IGNORE;
  802. dp.c_stair = c_cobble;
  803. // Fallback to using biome-defined stone
  804. } else {
  805. dp.c_wall = biome->c_stone;
  806. dp.c_alt_wall = CONTENT_IGNORE;
  807. dp.c_stair = biome->c_stone;
  808. }
  809. DungeonGen dgen(ndef, &gennotify, &dp);
  810. dgen.generate(vm, blockseed, full_node_min, full_node_max);
  811. }
  812. ////
  813. //// GenerateNotifier
  814. ////
  815. GenerateNotifier::GenerateNotifier(u32 notify_on,
  816. const std::set<u32> *notify_on_deco_ids,
  817. const std::set<std::string> *notify_on_custom)
  818. {
  819. m_notify_on = notify_on;
  820. m_notify_on_deco_ids = notify_on_deco_ids;
  821. m_notify_on_custom = notify_on_custom;
  822. }
  823. bool GenerateNotifier::addEvent(GenNotifyType type, v3s16 pos)
  824. {
  825. assert(type != GENNOTIFY_DECORATION && type != GENNOTIFY_CUSTOM);
  826. if (!shouldNotifyOn(type))
  827. return false;
  828. GenNotifyEvent gne;
  829. gne.type = type;
  830. gne.pos = pos;
  831. m_notify_events.emplace_back(std::move(gne));
  832. return true;
  833. }
  834. bool GenerateNotifier::addDecorationEvent(v3s16 pos, u32 id)
  835. {
  836. if (!shouldNotifyOn(GENNOTIFY_DECORATION))
  837. return false;
  838. // check if data relating to this decoration was requested
  839. assert(m_notify_on_deco_ids);
  840. if (m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->cend())
  841. return false;
  842. GenNotifyEvent gne;
  843. gne.type = GENNOTIFY_DECORATION;
  844. gne.pos = pos;
  845. gne.id = id;
  846. m_notify_events.emplace_back(std::move(gne));
  847. return true;
  848. }
  849. bool GenerateNotifier::setCustom(const std::string &key, const std::string &value)
  850. {
  851. if (!shouldNotifyOn(GENNOTIFY_CUSTOM))
  852. return false;
  853. // check if this key was requested to be saved
  854. assert(m_notify_on_custom);
  855. if (m_notify_on_custom->count(key) == 0)
  856. return false;
  857. m_notify_custom[key] = value;
  858. return true;
  859. }
  860. void GenerateNotifier::getEvents(
  861. std::map<std::string, std::vector<v3s16>> &event_map) const
  862. {
  863. for (auto &gn : m_notify_events) {
  864. assert(gn.type != GENNOTIFY_CUSTOM); // never stored in this list
  865. std::string name = (gn.type == GENNOTIFY_DECORATION) ?
  866. "decoration#"+ itos(gn.id) :
  867. flagdesc_gennotify[gn.type].name;
  868. event_map[name].push_back(gn.pos);
  869. }
  870. }
  871. void GenerateNotifier::clearEvents()
  872. {
  873. m_notify_events.clear();
  874. m_notify_custom.clear();
  875. }
  876. ////
  877. //// MapgenParams
  878. ////
  879. MapgenParams::~MapgenParams()
  880. {
  881. delete bparams;
  882. }
  883. void MapgenParams::readParams(const Settings *settings)
  884. {
  885. // should always be used via MapSettingsManager
  886. assert(settings != g_settings);
  887. std::string seed_str;
  888. if (settings->getNoEx("seed", seed_str)) {
  889. if (!seed_str.empty())
  890. seed = read_seed(seed_str.c_str());
  891. else
  892. myrand_bytes(&seed, sizeof(seed));
  893. }
  894. std::string mg_name;
  895. if (settings->getNoEx("mg_name", mg_name)) {
  896. mgtype = Mapgen::getMapgenType(mg_name);
  897. if (mgtype == MAPGEN_INVALID)
  898. mgtype = MAPGEN_DEFAULT;
  899. }
  900. settings->getS16NoEx("water_level", water_level);
  901. settings->getS16NoEx("mapgen_limit", mapgen_limit);
  902. settings->getS16NoEx("chunksize", chunksize);
  903. settings->getFlagStrNoEx("mg_flags", flags, flagdesc_mapgen);
  904. chunksize = rangelim(chunksize, 1, 10);
  905. delete bparams;
  906. bparams = BiomeManager::createBiomeParams(BIOMEGEN_ORIGINAL);
  907. if (bparams) {
  908. bparams->readParams(settings);
  909. bparams->seed = seed;
  910. }
  911. }
  912. void MapgenParams::writeParams(Settings *settings) const
  913. {
  914. settings->set("mg_name", Mapgen::getMapgenName(mgtype));
  915. settings->setU64("seed", seed);
  916. settings->setS16("water_level", water_level);
  917. settings->setS16("mapgen_limit", mapgen_limit);
  918. settings->setS16("chunksize", chunksize);
  919. settings->setFlagStr("mg_flags", flags, flagdesc_mapgen);
  920. if (bparams)
  921. bparams->writeParams(settings);
  922. }
  923. s32 MapgenParams::getSpawnRangeMax()
  924. {
  925. if (!m_mapgen_edges_calculated) {
  926. std::pair<s16, s16> edges = get_mapgen_edges(mapgen_limit, chunksize);
  927. mapgen_edge_min = edges.first;
  928. mapgen_edge_max = edges.second;
  929. m_mapgen_edges_calculated = true;
  930. }
  931. return MYMIN(-mapgen_edge_min, mapgen_edge_max);
  932. }
  933. std::pair<s16, s16> get_mapgen_edges(s16 mapgen_limit, s16 chunksize)
  934. {
  935. // Central chunk offset, in blocks
  936. s16 ccoff_b = -chunksize / 2;
  937. // Chunksize, in nodes
  938. s32 csize_n = chunksize * MAP_BLOCKSIZE;
  939. // Minp/maxp of central chunk, in nodes
  940. s16 ccmin = ccoff_b * MAP_BLOCKSIZE;
  941. s16 ccmax = ccmin + csize_n - 1;
  942. // Fullminp/fullmaxp of central chunk, in nodes
  943. s16 ccfmin = ccmin - MAP_BLOCKSIZE;
  944. s16 ccfmax = ccmax + MAP_BLOCKSIZE;
  945. // Effective mapgen limit, in blocks
  946. // Uses same calculation as ServerMap::blockpos_over_mapgen_limit(v3s16 p)
  947. s16 mapgen_limit_b = rangelim(mapgen_limit,
  948. 0, MAX_MAP_GENERATION_LIMIT) / MAP_BLOCKSIZE;
  949. // Effective mapgen limits, in nodes
  950. s16 mapgen_limit_min = -mapgen_limit_b * MAP_BLOCKSIZE;
  951. s16 mapgen_limit_max = (mapgen_limit_b + 1) * MAP_BLOCKSIZE - 1;
  952. // Number of complete chunks from central chunk fullminp/fullmaxp
  953. // to effective mapgen limits.
  954. s16 numcmin = MYMAX((ccfmin - mapgen_limit_min) / csize_n, 0);
  955. s16 numcmax = MYMAX((mapgen_limit_max - ccfmax) / csize_n, 0);
  956. // Mapgen edges, in nodes
  957. return std::pair<s16, s16>(ccmin - numcmin * csize_n, ccmax + numcmax * csize_n);
  958. }