]> git.lizzy.rs Git - minetest.git/blob - src/mapgen.cpp
Fix MSVC error caused by ed10005
[minetest.git] / src / mapgen.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
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
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "mapgen.h"
21 #include "voxel.h"
22 #include "noise.h"
23 #include "gamedef.h"
24 #include "mg_biome.h"
25 #include "mapblock.h"
26 #include "mapnode.h"
27 #include "map.h"
28 #include "content_sao.h"
29 #include "nodedef.h"
30 #include "emerge.h"
31 #include "content_mapnode.h" // For content_mapnode_get_new_name
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         {NULL,       0}
50 };
51
52 FlagDesc flagdesc_gennotify[] = {
53         {"dungeon",          1 << GENNOTIFY_DUNGEON},
54         {"temple",           1 << GENNOTIFY_TEMPLE},
55         {"cave_begin",       1 << GENNOTIFY_CAVE_BEGIN},
56         {"cave_end",         1 << GENNOTIFY_CAVE_END},
57         {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN},
58         {"large_cave_end",   1 << GENNOTIFY_LARGECAVE_END},
59         {"decoration",       1 << GENNOTIFY_DECORATION},
60         {NULL,               0}
61 };
62
63
64 ///////////////////////////////////////////////////////////////////////////////
65
66
67 Mapgen::Mapgen()
68 {
69         generating    = false;
70         id            = -1;
71         seed          = 0;
72         water_level   = 0;
73         flags         = 0;
74
75         vm          = NULL;
76         ndef        = NULL;
77         heightmap   = NULL;
78         biomemap    = NULL;
79 }
80
81
82 Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeManager *emerge) :
83         gennotify(emerge->gen_notify_on, &emerge->gen_notify_on_deco_ids)
84 {
85         generating    = false;
86         id            = mapgenid;
87         seed          = (int)params->seed;
88         water_level   = params->water_level;
89         flags         = params->flags;
90         csize         = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE);
91
92         vm        = NULL;
93         ndef      = NULL;
94         heightmap = NULL;
95         biomemap  = NULL;
96 }
97
98
99 Mapgen::~Mapgen()
100 {
101 }
102
103
104 u32 Mapgen::getBlockSeed(v3s16 p, int seed)
105 {
106         return (u32)seed   +
107                 p.Z * 38134234 +
108                 p.Y * 42123    +
109                 p.X * 23;
110 }
111
112
113 u32 Mapgen::getBlockSeed2(v3s16 p, int seed)
114 {
115         u32 n = 1619 * p.X + 31337 * p.Y + 52591 * p.Z + 1013 * seed;
116         n = (n >> 13) ^ n;
117         return (n * (n * n * 60493 + 19990303) + 1376312589);
118 }
119
120
121 // Returns Y one under area minimum if not found
122 s16 Mapgen::findGroundLevelFull(v2s16 p2d)
123 {
124         v3s16 em = vm->m_area.getExtent();
125         s16 y_nodes_max = vm->m_area.MaxEdge.Y;
126         s16 y_nodes_min = vm->m_area.MinEdge.Y;
127         u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y);
128         s16 y;
129
130         for (y = y_nodes_max; y >= y_nodes_min; y--) {
131                 MapNode &n = vm->m_data[i];
132                 if (ndef->get(n).walkable)
133                         break;
134
135                 vm->m_area.add_y(em, i, -1);
136         }
137         return (y >= y_nodes_min) ? y : y_nodes_min - 1;
138 }
139
140
141 // Returns -MAP_GENERATION_LIMIT if not found
142 s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax)
143 {
144         v3s16 em = vm->m_area.getExtent();
145         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
146         s16 y;
147
148         for (y = ymax; y >= ymin; y--) {
149                 MapNode &n = vm->m_data[i];
150                 if (ndef->get(n).walkable)
151                         break;
152
153                 vm->m_area.add_y(em, i, -1);
154         }
155         return (y >= ymin) ? y : -MAP_GENERATION_LIMIT;
156 }
157
158
159 void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax)
160 {
161         if (!heightmap)
162                 return;
163
164         //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
165         int index = 0;
166         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
167                 for (s16 x = nmin.X; x <= nmax.X; x++, index++) {
168                         s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
169
170                         heightmap[index] = y;
171                 }
172         }
173         //printf("updateHeightmap: %dus\n", t.stop());
174 }
175
176
177 void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax)
178 {
179         bool isliquid, wasliquid;
180         v3s16 em  = vm->m_area.getExtent();
181
182         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
183                 for (s16 x = nmin.X; x <= nmax.X; x++) {
184                         wasliquid = true;
185
186                         u32 i = vm->m_area.index(x, nmax.Y, z);
187                         for (s16 y = nmax.Y; y >= nmin.Y; y--) {
188                                 isliquid = ndef->get(vm->m_data[i]).isLiquid();
189
190                                 // there was a change between liquid and nonliquid, add to queue.
191                                 if (isliquid != wasliquid)
192                                         trans_liquid->push_back(v3s16(x, y, z));
193
194                                 wasliquid = isliquid;
195                                 vm->m_area.add_y(em, i, -1);
196                         }
197                 }
198         }
199 }
200
201
202 void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax)
203 {
204         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
205         VoxelArea a(nmin, nmax);
206
207         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
208                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
209                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
210                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
211                                 vm->m_data[i].param1 = light;
212                 }
213         }
214 }
215
216
217 void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light)
218 {
219         if (light <= 1 || !a.contains(p))
220                 return;
221
222         u32 vi = vm->m_area.index(p);
223         MapNode &nn = vm->m_data[vi];
224
225         light--;
226         // should probably compare masked, but doesn't seem to make a difference
227         if (light <= nn.param1 || !ndef->get(nn).light_propagates)
228                 return;
229
230         nn.param1 = light;
231
232         lightSpread(a, p + v3s16(0, 0, 1), light);
233         lightSpread(a, p + v3s16(0, 1, 0), light);
234         lightSpread(a, p + v3s16(1, 0, 0), light);
235         lightSpread(a, p - v3s16(0, 0, 1), light);
236         lightSpread(a, p - v3s16(0, 1, 0), light);
237         lightSpread(a, p - v3s16(1, 0, 0), light);
238 }
239
240
241 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax)
242 {
243         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
244         //TimeTaker t("updateLighting");
245
246         propagateSunlight(nmin, nmax);
247         spreadLight(full_nmin, full_nmax);
248
249         //printf("updateLighting: %dms\n", t.stop());
250 }
251
252
253
254 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax)
255 {
256         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
257         //TimeTaker t("updateLighting");
258
259         propagateSunlight(
260                 nmin - v3s16(1, 1, 1) * MAP_BLOCKSIZE,
261                 nmax + v3s16(1, 0, 1) * MAP_BLOCKSIZE);
262
263         spreadLight(
264                 nmin - v3s16(1, 1, 1) * MAP_BLOCKSIZE,
265                 nmax + v3s16(1, 1, 1) * MAP_BLOCKSIZE);
266
267         //printf("updateLighting: %dms\n", t.stop());
268 }
269
270
271 void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax)
272 {
273         //TimeTaker t("propagateSunlight");
274         VoxelArea a(nmin, nmax);
275         bool block_is_underground = (water_level >= nmax.Y);
276         v3s16 em = vm->m_area.getExtent();
277
278         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
279                 for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
280                         // see if we can get a light value from the overtop
281                         u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
282                         if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
283                                 if (block_is_underground)
284                                         continue;
285                         } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN) {
286                                 continue;
287                         }
288                         vm->m_area.add_y(em, i, -1);
289
290                         for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
291                                 MapNode &n = vm->m_data[i];
292                                 if (!ndef->get(n).sunlight_propagates)
293                                         break;
294                                 n.param1 = LIGHT_SUN;
295                                 vm->m_area.add_y(em, i, -1);
296                         }
297                 }
298         }
299         //printf("propagateSunlight: %dms\n", t.stop());
300 }
301
302
303
304 void Mapgen::spreadLight(v3s16 nmin, v3s16 nmax)
305 {
306         //TimeTaker t("spreadLight");
307         VoxelArea a(nmin, nmax);
308
309         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
310                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
311                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
312                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
313                                 MapNode &n = vm->m_data[i];
314                                 if (n.getContent() == CONTENT_IGNORE ||
315                                         !ndef->get(n).light_propagates)
316                                         continue;
317
318                                 u8 light_produced = ndef->get(n).light_source & 0x0F;
319                                 if (light_produced)
320                                         n.param1 = light_produced;
321
322                                 u8 light = n.param1 & 0x0F;
323                                 if (light) {
324                                         lightSpread(a, v3s16(x,     y,     z + 1), light);
325                                         lightSpread(a, v3s16(x,     y + 1, z    ), light);
326                                         lightSpread(a, v3s16(x + 1, y,     z    ), light);
327                                         lightSpread(a, v3s16(x,     y,     z - 1), light);
328                                         lightSpread(a, v3s16(x,     y - 1, z    ), light);
329                                         lightSpread(a, v3s16(x - 1, y,     z    ), light);
330                                 }
331                         }
332                 }
333         }
334
335         //printf("spreadLight: %dms\n", t.stop());
336 }
337
338
339
340 void Mapgen::calcLightingOld(v3s16 nmin, v3s16 nmax)
341 {
342         enum LightBank banks[2] = {LIGHTBANK_DAY, LIGHTBANK_NIGHT};
343         VoxelArea a(nmin, nmax);
344         bool block_is_underground = (water_level > nmax.Y);
345         bool sunlight = !block_is_underground;
346
347         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
348
349         for (int i = 0; i < 2; i++) {
350                 enum LightBank bank = banks[i];
351                 std::set<v3s16> light_sources;
352                 std::map<v3s16, u8> unlight_from;
353
354                 voxalgo::clearLightAndCollectSources(*vm, a, bank, ndef,
355                         light_sources, unlight_from);
356                 voxalgo::propagateSunlight(*vm, a, sunlight, light_sources, ndef);
357
358                 vm->unspreadLight(bank, unlight_from, light_sources, ndef);
359                 vm->spreadLight(bank, light_sources, ndef);
360         }
361 }
362
363
364 ///////////////////////////////////////////////////////////////////////////////
365
366 GenerateNotifier::GenerateNotifier()
367 {
368         m_notify_on = 0;
369 }
370
371
372 GenerateNotifier::GenerateNotifier(u32 notify_on,
373         std::set<u32> *notify_on_deco_ids)
374 {
375         m_notify_on = notify_on;
376         m_notify_on_deco_ids = notify_on_deco_ids;
377 }
378
379
380 void GenerateNotifier::setNotifyOn(u32 notify_on)
381 {
382         m_notify_on = notify_on;
383 }
384
385
386 void GenerateNotifier::setNotifyOnDecoIds(std::set<u32> *notify_on_deco_ids)
387 {
388         m_notify_on_deco_ids = notify_on_deco_ids;
389 }
390
391
392 bool GenerateNotifier::addEvent(GenNotifyType type, v3s16 pos, u32 id)
393 {
394         if (!(m_notify_on & (1 << type)))
395                 return false;
396
397         if (type == GENNOTIFY_DECORATION &&
398                 m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->end())
399                 return false;
400
401         GenNotifyEvent gne;
402         gne.type = type;
403         gne.pos  = pos;
404         gne.id   = id;
405         m_notify_events.push_back(gne);
406
407         return true;
408 }
409
410
411 void GenerateNotifier::getEvents(
412         std::map<std::string, std::vector<v3s16> > &event_map,
413         bool peek_events)
414 {
415         std::list<GenNotifyEvent>::iterator it;
416
417         for (it = m_notify_events.begin(); it != m_notify_events.end(); ++it) {
418                 GenNotifyEvent &gn = *it;
419                 std::string name = (gn.type == GENNOTIFY_DECORATION) ?
420                         "decoration#"+ itos(gn.id) :
421                         flagdesc_gennotify[gn.type].name;
422
423                 event_map[name].push_back(gn.pos);
424         }
425
426         if (!peek_events)
427                 m_notify_events.clear();
428 }
429
430
431 ///////////////////////////////////////////////////////////////////////////////
432
433
434 ObjDefManager::ObjDefManager(IGameDef *gamedef, ObjDefType type)
435 {
436         m_objtype = type;
437         m_ndef = gamedef->getNodeDefManager();
438 }
439
440
441 ObjDefManager::~ObjDefManager()
442 {
443         for (size_t i = 0; i != m_objects.size(); i++)
444                 delete m_objects[i];
445 }
446
447
448 ObjDefHandle ObjDefManager::add(ObjDef *obj)
449 {
450         assert(obj);
451
452         if (obj->name.length() && getByName(obj->name))
453                 return OBJDEF_INVALID_HANDLE;
454
455         u32 index = addRaw(obj);
456         if (index == OBJDEF_INVALID_INDEX)
457                 return OBJDEF_INVALID_HANDLE;
458
459         obj->handle = createHandle(index, m_objtype, obj->uid);
460         return obj->handle;
461 }
462
463
464 ObjDef *ObjDefManager::get(ObjDefHandle handle) const
465 {
466         u32 index = validateHandle(handle);
467         return (index != OBJDEF_INVALID_INDEX) ? getRaw(index) : NULL;
468 }
469
470
471 ObjDef *ObjDefManager::set(ObjDefHandle handle, ObjDef *obj)
472 {
473         u32 index = validateHandle(handle);
474         return (index != OBJDEF_INVALID_INDEX) ? setRaw(index, obj) : NULL;
475 }
476
477
478 u32 ObjDefManager::addRaw(ObjDef *obj)
479 {
480         size_t nobjects = m_objects.size();
481         if (nobjects >= OBJDEF_MAX_ITEMS)
482                 return -1;
483
484         obj->index = nobjects;
485
486         // Ensure UID is nonzero so that a valid handle == OBJDEF_INVALID_HANDLE
487         // is not possible.  The slight randomness bias isn't very significant.
488         obj->uid = myrand() & OBJDEF_UID_MASK;
489         if (obj->uid == 0)
490                 obj->uid = 1;
491
492         m_objects.push_back(obj);
493
494         infostream << "ObjDefManager: added " << getObjectTitle()
495                 << ": name=\"" << obj->name
496                 << "\" index=" << obj->index
497                 << " uid="     << obj->uid
498                 << std::endl;
499
500         return nobjects;
501 }
502
503
504 ObjDef *ObjDefManager::getRaw(u32 index) const
505 {
506         return m_objects[index];
507 }
508
509
510 ObjDef *ObjDefManager::setRaw(u32 index, ObjDef *obj)
511 {
512         ObjDef *old_obj = m_objects[index];
513         m_objects[index] = obj;
514         return old_obj;
515 }
516
517
518 ObjDef *ObjDefManager::getByName(const std::string &name) const
519 {
520         for (size_t i = 0; i != m_objects.size(); i++) {
521                 ObjDef *obj = m_objects[i];
522                 if (obj && !strcasecmp(name.c_str(), obj->name.c_str()))
523                         return obj;
524         }
525
526         return NULL;
527 }
528
529
530 void ObjDefManager::clear()
531 {
532         for (size_t i = 0; i != m_objects.size(); i++)
533                 delete m_objects[i];
534
535         m_objects.clear();
536 }
537
538
539 u32 ObjDefManager::validateHandle(ObjDefHandle handle) const
540 {
541         ObjDefType type;
542         u32 index;
543         u32 uid;
544
545         bool is_valid =
546                 (handle != OBJDEF_INVALID_HANDLE)         &&
547                 decodeHandle(handle, &index, &type, &uid) &&
548                 (type == m_objtype)                       &&
549                 (index < m_objects.size())                &&
550                 (m_objects[index]->uid == uid);
551
552         return is_valid ? index : -1;
553 }
554
555
556 ObjDefHandle ObjDefManager::createHandle(u32 index, ObjDefType type, u32 uid)
557 {
558         ObjDefHandle handle = 0;
559         set_bits(&handle, 0, 18, index);
560         set_bits(&handle, 18, 6, type);
561         set_bits(&handle, 24, 7, uid);
562
563         u32 parity = calc_parity(handle);
564         set_bits(&handle, 31, 1, parity);
565
566         return handle ^ OBJDEF_HANDLE_SALT;
567 }
568
569
570 bool ObjDefManager::decodeHandle(ObjDefHandle handle, u32 *index,
571         ObjDefType *type, u32 *uid)
572 {
573         handle ^= OBJDEF_HANDLE_SALT;
574
575         u32 parity = get_bits(handle, 31, 1);
576         set_bits(&handle, 31, 1, 0);
577         if (parity != calc_parity(handle))
578                 return false;
579
580         *index = get_bits(handle, 0, 18);
581         *type  = (ObjDefType)get_bits(handle, 18, 6);
582         *uid   = get_bits(handle, 24, 7);
583         return true;
584 }
585
586
587 ///////////////////////////////////////////////////////////////////////////////
588
589
590 void MapgenParams::load(const Settings &settings)
591 {
592         std::string seed_str;
593         const char *seed_name = (&settings == g_settings) ? "fixed_map_seed" : "seed";
594
595         if (settings.getNoEx(seed_name, seed_str) && !seed_str.empty())
596                 seed = read_seed(seed_str.c_str());
597         else
598                 myrand_bytes(&seed, sizeof(seed));
599
600         settings.getNoEx("mg_name", mg_name);
601         settings.getS16NoEx("water_level", water_level);
602         settings.getS16NoEx("chunksize", chunksize);
603         settings.getFlagStrNoEx("mg_flags", flags, flagdesc_mapgen);
604         settings.getNoiseParams("mg_biome_np_heat", np_biome_heat);
605         settings.getNoiseParams("mg_biome_np_humidity", np_biome_humidity);
606
607         delete sparams;
608         sparams = EmergeManager::createMapgenParams(mg_name);
609         if (sparams)
610                 sparams->readParams(&settings);
611 }
612
613
614 void MapgenParams::save(Settings &settings) const
615 {
616         settings.set("mg_name", mg_name);
617         settings.setU64("seed", seed);
618         settings.setS16("water_level", water_level);
619         settings.setS16("chunksize", chunksize);
620         settings.setFlagStr("mg_flags", flags, flagdesc_mapgen, (u32)-1);
621         settings.setNoiseParams("mg_biome_np_heat", np_biome_heat);
622         settings.setNoiseParams("mg_biome_np_humidity", np_biome_humidity);
623
624         if (sparams)
625                 sparams->writeParams(&settings);
626 }
627