Mapgen: Spread both night and day light banks in spreadLight
[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         heightmap = NULL;
80         biomemap  = NULL;
81         heatmap   = NULL;
82         humidmap  = NULL;
83 }
84
85
86 Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeManager *emerge) :
87         gennotify(emerge->gen_notify_on, &emerge->gen_notify_on_deco_ids)
88 {
89         generating  = false;
90         id          = mapgenid;
91         seed        = (int)params->seed;
92         water_level = params->water_level;
93         flags       = params->flags;
94         csize       = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE);
95
96         vm        = NULL;
97         ndef      = NULL;
98         heightmap = NULL;
99         biomemap  = NULL;
100         heatmap   = NULL;
101         humidmap  = NULL;
102 }
103
104
105 Mapgen::~Mapgen()
106 {
107 }
108
109
110 u32 Mapgen::getBlockSeed(v3s16 p, int seed)
111 {
112         return (u32)seed   +
113                 p.Z * 38134234 +
114                 p.Y * 42123    +
115                 p.X * 23;
116 }
117
118
119 u32 Mapgen::getBlockSeed2(v3s16 p, int seed)
120 {
121         u32 n = 1619 * p.X + 31337 * p.Y + 52591 * p.Z + 1013 * seed;
122         n = (n >> 13) ^ n;
123         return (n * (n * n * 60493 + 19990303) + 1376312589);
124 }
125
126
127 // Returns Y one under area minimum if not found
128 s16 Mapgen::findGroundLevelFull(v2s16 p2d)
129 {
130         v3s16 em = vm->m_area.getExtent();
131         s16 y_nodes_max = vm->m_area.MaxEdge.Y;
132         s16 y_nodes_min = vm->m_area.MinEdge.Y;
133         u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y);
134         s16 y;
135
136         for (y = y_nodes_max; y >= y_nodes_min; y--) {
137                 MapNode &n = vm->m_data[i];
138                 if (ndef->get(n).walkable)
139                         break;
140
141                 vm->m_area.add_y(em, i, -1);
142         }
143         return (y >= y_nodes_min) ? y : y_nodes_min - 1;
144 }
145
146
147 // Returns -MAX_MAP_GENERATION_LIMIT if not found
148 s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax)
149 {
150         v3s16 em = vm->m_area.getExtent();
151         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
152         s16 y;
153
154         for (y = ymax; y >= ymin; y--) {
155                 MapNode &n = vm->m_data[i];
156                 if (ndef->get(n).walkable)
157                         break;
158
159                 vm->m_area.add_y(em, i, -1);
160         }
161         return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT;
162 }
163
164
165 // Returns -MAX_MAP_GENERATION_LIMIT if not found or if ground is found first
166 s16 Mapgen::findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax)
167 {
168         v3s16 em = vm->m_area.getExtent();
169         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
170         s16 y;
171
172         for (y = ymax; y >= ymin; y--) {
173                 MapNode &n = vm->m_data[i];
174                 if (ndef->get(n).walkable)
175                         return -MAX_MAP_GENERATION_LIMIT;
176                 else if (ndef->get(n).isLiquid())
177                         break;
178
179                 vm->m_area.add_y(em, i, -1);
180         }
181         return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT;
182 }
183
184
185 void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax)
186 {
187         if (!heightmap)
188                 return;
189
190         //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
191         int index = 0;
192         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
193                 for (s16 x = nmin.X; x <= nmax.X; x++, index++) {
194                         s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
195
196                         heightmap[index] = y;
197                 }
198         }
199         //printf("updateHeightmap: %dus\n", t.stop());
200 }
201
202
203 void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax)
204 {
205         bool isliquid, wasliquid;
206         v3s16 em  = vm->m_area.getExtent();
207
208         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
209                 for (s16 x = nmin.X; x <= nmax.X; x++) {
210                         wasliquid = true;
211
212                         u32 i = vm->m_area.index(x, nmax.Y, z);
213                         for (s16 y = nmax.Y; y >= nmin.Y; y--) {
214                                 isliquid = ndef->get(vm->m_data[i]).isLiquid();
215
216                                 // there was a change between liquid and nonliquid, add to queue.
217                                 if (isliquid != wasliquid)
218                                         trans_liquid->push_back(v3s16(x, y, z));
219
220                                 wasliquid = isliquid;
221                                 vm->m_area.add_y(em, i, -1);
222                         }
223                 }
224         }
225 }
226
227
228 void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax)
229 {
230         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
231         VoxelArea a(nmin, nmax);
232
233         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
234                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
235                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
236                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
237                                 vm->m_data[i].param1 = light;
238                 }
239         }
240 }
241
242
243 void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light)
244 {
245         if (light <= 1)
246                 return;
247
248         u32 vi = vm->m_area.index(p);
249         if (!a.contains(vi))
250                 return;
251
252         MapNode &n = vm->m_data[vi];
253
254         // Decay light in each of the banks separately
255         u8 light_day = light & 0x0F;
256         if (light_day > 0)
257                 light_day -= 0x01;
258
259         u8 light_night = light & 0xF0;
260         if (light_night > 0)
261                 light_night -= 0x10;
262
263         // Bail out only if we have no more light from either bank to propogate, or
264         // we hit a solid block that light cannot pass through.
265         if ((light_day  <= (n.param1 & 0x0F) &&
266                 light_night <= (n.param1 & 0xF0)) ||
267                 !ndef->get(n).light_propagates)
268                 return;
269
270         // Since this recursive function only terminates when there is no light from
271         // either bank left, we need to take the max of both banks into account for
272         // the case where spreading has stopped for one light bank but not the other.
273         light = MYMAX(light_day, n.param1 & 0x0F) |
274                         MYMAX(light_night, n.param1 & 0xF0);
275
276         n.param1 = light;
277
278         lightSpread(a, p + v3s16(0, 0, 1), light);
279         lightSpread(a, p + v3s16(0, 1, 0), light);
280         lightSpread(a, p + v3s16(1, 0, 0), light);
281         lightSpread(a, p - v3s16(0, 0, 1), light);
282         lightSpread(a, p - v3s16(0, 1, 0), light);
283         lightSpread(a, p - v3s16(1, 0, 0), light);
284 }
285
286
287 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax,
288         bool propagate_shadow)
289 {
290         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
291         //TimeTaker t("updateLighting");
292
293         propagateSunlight(nmin, nmax, propagate_shadow);
294         spreadLight(full_nmin, full_nmax);
295
296         //printf("updateLighting: %dms\n", t.stop());
297 }
298
299
300 void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow)
301 {
302         //TimeTaker t("propagateSunlight");
303         VoxelArea a(nmin, nmax);
304         bool block_is_underground = (water_level >= nmax.Y);
305         v3s16 em = vm->m_area.getExtent();
306
307         // NOTE: Direct access to the low 4 bits of param1 is okay here because,
308         // by definition, sunlight will never be in the night lightbank.
309
310         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
311                 for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
312                         // see if we can get a light value from the overtop
313                         u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
314                         if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
315                                 if (block_is_underground)
316                                         continue;
317                         } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN &&
318                                         propagate_shadow) {
319                                 continue;
320                         }
321                         vm->m_area.add_y(em, i, -1);
322
323                         for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
324                                 MapNode &n = vm->m_data[i];
325                                 if (!ndef->get(n).sunlight_propagates)
326                                         break;
327                                 n.param1 = LIGHT_SUN;
328                                 vm->m_area.add_y(em, i, -1);
329                         }
330                 }
331         }
332         //printf("propagateSunlight: %dms\n", t.stop());
333 }
334
335
336 void Mapgen::spreadLight(v3s16 nmin, v3s16 nmax)
337 {
338         //TimeTaker t("spreadLight");
339         VoxelArea a(nmin, nmax);
340
341         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
342                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
343                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
344                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
345                                 MapNode &n = vm->m_data[i];
346                                 if (n.getContent() == CONTENT_IGNORE)
347                                         continue;
348
349                                 const ContentFeatures &cf = ndef->get(n);
350                                 if (!cf.light_propagates)
351                                         continue;
352
353                                 // TODO(hmmmmm): Abstract away direct param1 accesses with a
354                                 // wrapper, but something lighter than MapNode::get/setLight
355
356                                 u8 light_produced = cf.light_source;
357                                 if (light_produced)
358                                         n.param1 = light_produced | (light_produced << 4);
359
360                                 u8 light = n.param1;
361                                 if (light) {
362                                         lightSpread(a, v3s16(x,     y,     z + 1), light);
363                                         lightSpread(a, v3s16(x,     y + 1, z    ), light);
364                                         lightSpread(a, v3s16(x + 1, y,     z    ), light);
365                                         lightSpread(a, v3s16(x,     y,     z - 1), light);
366                                         lightSpread(a, v3s16(x,     y - 1, z    ), light);
367                                         lightSpread(a, v3s16(x - 1, y,     z    ), light);
368                                 }
369                         }
370                 }
371         }
372
373         //printf("spreadLight: %dms\n", t.stop());
374 }
375
376
377 ////
378 //// GenerateNotifier
379 ////
380
381 GenerateNotifier::GenerateNotifier()
382 {
383         m_notify_on = 0;
384 }
385
386
387 GenerateNotifier::GenerateNotifier(u32 notify_on,
388         std::set<u32> *notify_on_deco_ids)
389 {
390         m_notify_on = notify_on;
391         m_notify_on_deco_ids = notify_on_deco_ids;
392 }
393
394
395 void GenerateNotifier::setNotifyOn(u32 notify_on)
396 {
397         m_notify_on = notify_on;
398 }
399
400
401 void GenerateNotifier::setNotifyOnDecoIds(std::set<u32> *notify_on_deco_ids)
402 {
403         m_notify_on_deco_ids = notify_on_deco_ids;
404 }
405
406
407 bool GenerateNotifier::addEvent(GenNotifyType type, v3s16 pos, u32 id)
408 {
409         if (!(m_notify_on & (1 << type)))
410                 return false;
411
412         if (type == GENNOTIFY_DECORATION &&
413                 m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->end())
414                 return false;
415
416         GenNotifyEvent gne;
417         gne.type = type;
418         gne.pos  = pos;
419         gne.id   = id;
420         m_notify_events.push_back(gne);
421
422         return true;
423 }
424
425
426 void GenerateNotifier::getEvents(
427         std::map<std::string, std::vector<v3s16> > &event_map,
428         bool peek_events)
429 {
430         std::list<GenNotifyEvent>::iterator it;
431
432         for (it = m_notify_events.begin(); it != m_notify_events.end(); ++it) {
433                 GenNotifyEvent &gn = *it;
434                 std::string name = (gn.type == GENNOTIFY_DECORATION) ?
435                         "decoration#"+ itos(gn.id) :
436                         flagdesc_gennotify[gn.type].name;
437
438                 event_map[name].push_back(gn.pos);
439         }
440
441         if (!peek_events)
442                 m_notify_events.clear();
443 }
444
445
446 ////
447 //// MapgenParams
448 ////
449
450 void MapgenParams::load(const Settings &settings)
451 {
452         std::string seed_str;
453         const char *seed_name = (&settings == g_settings) ? "fixed_map_seed" : "seed";
454
455         if (settings.getNoEx(seed_name, seed_str) && !seed_str.empty())
456                 seed = read_seed(seed_str.c_str());
457         else
458                 myrand_bytes(&seed, sizeof(seed));
459
460         settings.getNoEx("mg_name", mg_name);
461         settings.getS16NoEx("water_level", water_level);
462         settings.getS16NoEx("chunksize", chunksize);
463         settings.getFlagStrNoEx("mg_flags", flags, flagdesc_mapgen);
464         settings.getNoiseParams("mg_biome_np_heat", np_biome_heat);
465         settings.getNoiseParams("mg_biome_np_heat_blend", np_biome_heat_blend);
466         settings.getNoiseParams("mg_biome_np_humidity", np_biome_humidity);
467         settings.getNoiseParams("mg_biome_np_humidity_blend", np_biome_humidity_blend);
468
469         delete sparams;
470         MapgenFactory *mgfactory = EmergeManager::getMapgenFactory(mg_name);
471         if (mgfactory) {
472                 sparams = mgfactory->createMapgenParams();
473                 sparams->readParams(&settings);
474         }
475 }
476
477
478 void MapgenParams::save(Settings &settings) const
479 {
480         settings.set("mg_name", mg_name);
481         settings.setU64("seed", seed);
482         settings.setS16("water_level", water_level);
483         settings.setS16("chunksize", chunksize);
484         settings.setFlagStr("mg_flags", flags, flagdesc_mapgen, U32_MAX);
485         settings.setNoiseParams("mg_biome_np_heat", np_biome_heat);
486         settings.setNoiseParams("mg_biome_np_heat_blend", np_biome_heat_blend);
487         settings.setNoiseParams("mg_biome_np_humidity", np_biome_humidity);
488         settings.setNoiseParams("mg_biome_np_humidity_blend", np_biome_humidity_blend);
489
490         if (sparams)
491                 sparams->writeParams(&settings);
492 }