Move biome calculation to BiomeGen
[oweals/minetest.git] / src / mapgen.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2015 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
4 Copyright (C) 2010-2015 celeron55, Perttu Ahola <celeron55@gmail.com>
5
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
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "mapgen.h"
22 #include "voxel.h"
23 #include "noise.h"
24 #include "gamedef.h"
25 #include "mg_biome.h"
26 #include "mapblock.h"
27 #include "mapnode.h"
28 #include "map.h"
29 #include "content_sao.h"
30 #include "nodedef.h"
31 #include "emerge.h"
32 #include "voxelalgorithms.h"
33 #include "porting.h"
34 #include "profiler.h"
35 #include "settings.h"
36 #include "treegen.h"
37 #include "serialization.h"
38 #include "util/serialize.h"
39 #include "util/numeric.h"
40 #include "filesys.h"
41 #include "log.h"
42
43 FlagDesc flagdesc_mapgen[] = {
44         {"trees",       MG_TREES},
45         {"caves",       MG_CAVES},
46         {"dungeons",    MG_DUNGEONS},
47         {"flat",        MG_FLAT},
48         {"light",       MG_LIGHT},
49         {"decorations", MG_DECORATIONS},
50         {NULL,       0}
51 };
52
53 FlagDesc flagdesc_gennotify[] = {
54         {"dungeon",          1 << GENNOTIFY_DUNGEON},
55         {"temple",           1 << GENNOTIFY_TEMPLE},
56         {"cave_begin",       1 << GENNOTIFY_CAVE_BEGIN},
57         {"cave_end",         1 << GENNOTIFY_CAVE_END},
58         {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN},
59         {"large_cave_end",   1 << GENNOTIFY_LARGECAVE_END},
60         {"decoration",       1 << GENNOTIFY_DECORATION},
61         {NULL,               0}
62 };
63
64
65 ////
66 //// Mapgen
67 ////
68
69 Mapgen::Mapgen()
70 {
71         generating  = false;
72         id          = -1;
73         seed        = 0;
74         water_level = 0;
75         flags       = 0;
76
77         vm        = NULL;
78         ndef      = NULL;
79         biomegen  = NULL;
80         biomemap  = NULL;
81         heightmap = NULL;
82 }
83
84
85 Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeManager *emerge) :
86         gennotify(emerge->gen_notify_on, &emerge->gen_notify_on_deco_ids)
87 {
88         generating  = false;
89         id          = mapgenid;
90         seed        = (int)params->seed;
91         water_level = params->water_level;
92         flags       = params->flags;
93         csize       = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE);
94
95         vm        = NULL;
96         ndef      = emerge->ndef;
97         biomegen  = NULL;
98         biomemap  = NULL;
99         heightmap = NULL;
100 }
101
102
103 Mapgen::~Mapgen()
104 {
105 }
106
107
108 u32 Mapgen::getBlockSeed(v3s16 p, int seed)
109 {
110         return (u32)seed   +
111                 p.Z * 38134234 +
112                 p.Y * 42123    +
113                 p.X * 23;
114 }
115
116
117 u32 Mapgen::getBlockSeed2(v3s16 p, int seed)
118 {
119         u32 n = 1619 * p.X + 31337 * p.Y + 52591 * p.Z + 1013 * seed;
120         n = (n >> 13) ^ n;
121         return (n * (n * n * 60493 + 19990303) + 1376312589);
122 }
123
124
125 // Returns Y one under area minimum if not found
126 s16 Mapgen::findGroundLevelFull(v2s16 p2d)
127 {
128         v3s16 em = vm->m_area.getExtent();
129         s16 y_nodes_max = vm->m_area.MaxEdge.Y;
130         s16 y_nodes_min = vm->m_area.MinEdge.Y;
131         u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y);
132         s16 y;
133
134         for (y = y_nodes_max; y >= y_nodes_min; y--) {
135                 MapNode &n = vm->m_data[i];
136                 if (ndef->get(n).walkable)
137                         break;
138
139                 vm->m_area.add_y(em, i, -1);
140         }
141         return (y >= y_nodes_min) ? y : y_nodes_min - 1;
142 }
143
144
145 // Returns -MAX_MAP_GENERATION_LIMIT if not found
146 s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax)
147 {
148         v3s16 em = vm->m_area.getExtent();
149         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
150         s16 y;
151
152         for (y = ymax; y >= ymin; y--) {
153                 MapNode &n = vm->m_data[i];
154                 if (ndef->get(n).walkable)
155                         break;
156
157                 vm->m_area.add_y(em, i, -1);
158         }
159         return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT;
160 }
161
162
163 // Returns -MAX_MAP_GENERATION_LIMIT if not found or if ground is found first
164 s16 Mapgen::findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax)
165 {
166         v3s16 em = vm->m_area.getExtent();
167         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
168         s16 y;
169
170         for (y = ymax; y >= ymin; y--) {
171                 MapNode &n = vm->m_data[i];
172                 if (ndef->get(n).walkable)
173                         return -MAX_MAP_GENERATION_LIMIT;
174                 else if (ndef->get(n).isLiquid())
175                         break;
176
177                 vm->m_area.add_y(em, i, -1);
178         }
179         return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT;
180 }
181
182
183 void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax)
184 {
185         if (!heightmap)
186                 return;
187
188         //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
189         int index = 0;
190         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
191                 for (s16 x = nmin.X; x <= nmax.X; x++, index++) {
192                         s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
193
194                         heightmap[index] = y;
195                 }
196         }
197         //printf("updateHeightmap: %dus\n", t.stop());
198 }
199
200
201 void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax)
202 {
203         bool isliquid, wasliquid;
204         v3s16 em  = vm->m_area.getExtent();
205
206         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
207                 for (s16 x = nmin.X; x <= nmax.X; x++) {
208                         wasliquid = true;
209
210                         u32 i = vm->m_area.index(x, nmax.Y, z);
211                         for (s16 y = nmax.Y; y >= nmin.Y; y--) {
212                                 isliquid = ndef->get(vm->m_data[i]).isLiquid();
213
214                                 // there was a change between liquid and nonliquid, add to queue.
215                                 if (isliquid != wasliquid)
216                                         trans_liquid->push_back(v3s16(x, y, z));
217
218                                 wasliquid = isliquid;
219                                 vm->m_area.add_y(em, i, -1);
220                         }
221                 }
222         }
223 }
224
225
226 void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax)
227 {
228         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
229         VoxelArea a(nmin, nmax);
230
231         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
232                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
233                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
234                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
235                                 vm->m_data[i].param1 = light;
236                 }
237         }
238 }
239
240
241 void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light)
242 {
243         if (light <= 1 || !a.contains(p))
244                 return;
245
246         u32 vi = vm->m_area.index(p);
247         MapNode &n = vm->m_data[vi];
248
249         // Decay light in each of the banks separately
250         u8 light_day = light & 0x0F;
251         if (light_day > 0)
252                 light_day -= 0x01;
253
254         u8 light_night = light & 0xF0;
255         if (light_night > 0)
256                 light_night -= 0x10;
257
258         // Bail out only if we have no more light from either bank to propogate, or
259         // we hit a solid block that light cannot pass through.
260         if ((light_day  <= (n.param1 & 0x0F) &&
261                 light_night <= (n.param1 & 0xF0)) ||
262                 !ndef->get(n).light_propagates)
263                 return;
264
265         // Since this recursive function only terminates when there is no light from
266         // either bank left, we need to take the max of both banks into account for
267         // the case where spreading has stopped for one light bank but not the other.
268         light = MYMAX(light_day, n.param1 & 0x0F) |
269                         MYMAX(light_night, n.param1 & 0xF0);
270
271         n.param1 = light;
272
273         lightSpread(a, p + v3s16(0, 0, 1), light);
274         lightSpread(a, p + v3s16(0, 1, 0), light);
275         lightSpread(a, p + v3s16(1, 0, 0), light);
276         lightSpread(a, p - v3s16(0, 0, 1), light);
277         lightSpread(a, p - v3s16(0, 1, 0), light);
278         lightSpread(a, p - v3s16(1, 0, 0), light);
279 }
280
281
282 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax,
283         bool propagate_shadow)
284 {
285         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
286         //TimeTaker t("updateLighting");
287
288         propagateSunlight(nmin, nmax, propagate_shadow);
289         spreadLight(full_nmin, full_nmax);
290
291         //printf("updateLighting: %dms\n", t.stop());
292 }
293
294
295 void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow)
296 {
297         //TimeTaker t("propagateSunlight");
298         VoxelArea a(nmin, nmax);
299         bool block_is_underground = (water_level >= nmax.Y);
300         v3s16 em = vm->m_area.getExtent();
301
302         // NOTE: Direct access to the low 4 bits of param1 is okay here because,
303         // by definition, sunlight will never be in the night lightbank.
304
305         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
306                 for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
307                         // see if we can get a light value from the overtop
308                         u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
309                         if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
310                                 if (block_is_underground)
311                                         continue;
312                         } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN &&
313                                         propagate_shadow) {
314                                 continue;
315                         }
316                         vm->m_area.add_y(em, i, -1);
317
318                         for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
319                                 MapNode &n = vm->m_data[i];
320                                 if (!ndef->get(n).sunlight_propagates)
321                                         break;
322                                 n.param1 = LIGHT_SUN;
323                                 vm->m_area.add_y(em, i, -1);
324                         }
325                 }
326         }
327         //printf("propagateSunlight: %dms\n", t.stop());
328 }
329
330
331 void Mapgen::spreadLight(v3s16 nmin, v3s16 nmax)
332 {
333         //TimeTaker t("spreadLight");
334         VoxelArea a(nmin, nmax);
335
336         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
337                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
338                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
339                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
340                                 MapNode &n = vm->m_data[i];
341                                 if (n.getContent() == CONTENT_IGNORE)
342                                         continue;
343
344                                 const ContentFeatures &cf = ndef->get(n);
345                                 if (!cf.light_propagates)
346                                         continue;
347
348                                 // TODO(hmmmmm): Abstract away direct param1 accesses with a
349                                 // wrapper, but something lighter than MapNode::get/setLight
350
351                                 u8 light_produced = cf.light_source;
352                                 if (light_produced)
353                                         n.param1 = light_produced | (light_produced << 4);
354
355                                 u8 light = n.param1;
356                                 if (light) {
357                                         lightSpread(a, v3s16(x,     y,     z + 1), light);
358                                         lightSpread(a, v3s16(x,     y + 1, z    ), light);
359                                         lightSpread(a, v3s16(x + 1, y,     z    ), light);
360                                         lightSpread(a, v3s16(x,     y,     z - 1), light);
361                                         lightSpread(a, v3s16(x,     y - 1, z    ), light);
362                                         lightSpread(a, v3s16(x - 1, y,     z    ), light);
363                                 }
364                         }
365                 }
366         }
367
368         //printf("spreadLight: %dms\n", t.stop());
369 }
370
371
372 ////
373 //// GenerateNotifier
374 ////
375
376 GenerateNotifier::GenerateNotifier()
377 {
378         m_notify_on = 0;
379 }
380
381
382 GenerateNotifier::GenerateNotifier(u32 notify_on,
383         std::set<u32> *notify_on_deco_ids)
384 {
385         m_notify_on = notify_on;
386         m_notify_on_deco_ids = notify_on_deco_ids;
387 }
388
389
390 void GenerateNotifier::setNotifyOn(u32 notify_on)
391 {
392         m_notify_on = notify_on;
393 }
394
395
396 void GenerateNotifier::setNotifyOnDecoIds(std::set<u32> *notify_on_deco_ids)
397 {
398         m_notify_on_deco_ids = notify_on_deco_ids;
399 }
400
401
402 bool GenerateNotifier::addEvent(GenNotifyType type, v3s16 pos, u32 id)
403 {
404         if (!(m_notify_on & (1 << type)))
405                 return false;
406
407         if (type == GENNOTIFY_DECORATION &&
408                 m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->end())
409                 return false;
410
411         GenNotifyEvent gne;
412         gne.type = type;
413         gne.pos  = pos;
414         gne.id   = id;
415         m_notify_events.push_back(gne);
416
417         return true;
418 }
419
420
421 void GenerateNotifier::getEvents(
422         std::map<std::string, std::vector<v3s16> > &event_map,
423         bool peek_events)
424 {
425         std::list<GenNotifyEvent>::iterator it;
426
427         for (it = m_notify_events.begin(); it != m_notify_events.end(); ++it) {
428                 GenNotifyEvent &gn = *it;
429                 std::string name = (gn.type == GENNOTIFY_DECORATION) ?
430                         "decoration#"+ itos(gn.id) :
431                         flagdesc_gennotify[gn.type].name;
432
433                 event_map[name].push_back(gn.pos);
434         }
435
436         if (!peek_events)
437                 m_notify_events.clear();
438 }
439
440
441 ////
442 //// MapgenParams
443 ////
444
445
446 MapgenParams::~MapgenParams()
447 {
448         delete bparams;
449         delete sparams;
450 }
451
452
453 void MapgenParams::load(const Settings &settings)
454 {
455         std::string seed_str;
456         const char *seed_name = (&settings == g_settings) ? "fixed_map_seed" : "seed";
457
458         if (settings.getNoEx(seed_name, seed_str) && !seed_str.empty())
459                 seed = read_seed(seed_str.c_str());
460         else
461                 myrand_bytes(&seed, sizeof(seed));
462
463         settings.getNoEx("mg_name", mg_name);
464         settings.getS16NoEx("water_level", water_level);
465         settings.getS16NoEx("chunksize", chunksize);
466         settings.getFlagStrNoEx("mg_flags", flags, flagdesc_mapgen);
467
468         delete bparams;
469         bparams = BiomeManager::createBiomeParams(BIOMEGEN_ORIGINAL);
470         if (bparams) {
471                 bparams->readParams(&settings);
472                 bparams->seed = seed;
473         }
474
475         delete sparams;
476         MapgenFactory *mgfactory = EmergeManager::getMapgenFactory(mg_name);
477         if (mgfactory) {
478                 sparams = mgfactory->createMapgenParams();
479                 sparams->readParams(&settings);
480         }
481 }
482
483
484 void MapgenParams::save(Settings &settings) const
485 {
486         settings.set("mg_name", mg_name);
487         settings.setU64("seed", seed);
488         settings.setS16("water_level", water_level);
489         settings.setS16("chunksize", chunksize);
490         settings.setFlagStr("mg_flags", flags, flagdesc_mapgen, U32_MAX);
491
492         if (bparams)
493                 bparams->writeParams(&settings);
494
495         if (sparams)
496                 sparams->writeParams(&settings);
497 }