]> git.lizzy.rs Git - dragonfireclient.git/blob - src/mapgen.cpp
Weather backward compatibility
[dragonfireclient.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 "biome.h"
24 #include "mapblock.h"
25 #include "mapnode.h"
26 #include "map.h"
27 //#include "serverobject.h"
28 #include "content_sao.h"
29 #include "nodedef.h"
30 #include "content_mapnode.h" // For content_mapnode_get_new_name
31 #include "voxelalgorithms.h"
32 #include "profiler.h"
33 #include "settings.h" // For g_settings
34 #include "main.h" // For g_profiler
35 #include "treegen.h"
36 #include "mapgen_v6.h"
37 #include "mapgen_v7.h"
38 #include "util/serialize.h"
39
40 FlagDesc flagdesc_mapgen[] = {
41         {"trees",          MG_TREES},
42         {"caves",          MG_CAVES},
43         {"dungeons",       MG_DUNGEONS},
44         {"v6_jungles",     MGV6_JUNGLES},
45         {"v6_biome_blend", MGV6_BIOME_BLEND},
46         {"flat",           MG_FLAT},
47         {"nolight",        MG_NOLIGHT},
48         {NULL,             0}
49 };
50
51 FlagDesc flagdesc_ore[] = {
52         {"absheight",            OREFLAG_ABSHEIGHT},
53         {"scatter_noisedensity", OREFLAG_DENSITY},
54         {"claylike_nodeisnt",    OREFLAG_NODEISNT},
55         {NULL,                   0}
56 };
57
58 FlagDesc flagdesc_deco_schematic[] = {
59         {"place_center_x", DECO_PLACE_CENTER_X},
60         {"place_center_y", DECO_PLACE_CENTER_Y},
61         {"place_center_z", DECO_PLACE_CENTER_Z},
62         {NULL,             0}
63 };
64
65 ///////////////////////////////////////////////////////////////////////////////
66
67
68 Ore *createOre(OreType type) {
69         switch (type) {
70                 case ORE_SCATTER:
71                         return new OreScatter;
72                 case ORE_SHEET:
73                         return new OreSheet;
74                 //case ORE_CLAYLIKE: //TODO: implement this!
75                 //      return new OreClaylike;
76                 default:
77                         return NULL;
78         }
79 }
80
81
82 Ore::~Ore() {
83         delete np;
84         delete noise;
85 }
86
87
88 void Ore::resolveNodeNames(INodeDefManager *ndef) {
89         if (ore == CONTENT_IGNORE) {
90                 ore = ndef->getId(ore_name);
91                 if (ore == CONTENT_IGNORE) {
92                         errorstream << "Ore::resolveNodeNames: ore node '"
93                                 << ore_name << "' not defined";
94                         ore     = CONTENT_AIR;
95                         wherein = CONTENT_AIR;
96                 }
97         }
98
99         if (wherein == CONTENT_IGNORE) {
100                 wherein = ndef->getId(wherein_name);
101                 if (wherein == CONTENT_IGNORE) {
102                         errorstream << "Ore::resolveNodeNames: wherein node '"
103                                 << wherein_name << "' not defined";
104                         ore     = CONTENT_AIR;
105                         wherein = CONTENT_AIR;
106                 }
107         }
108 }
109
110
111 void Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
112         int in_range = 0;
113
114         in_range |= (nmin.Y <= height_max && nmax.Y >= height_min);
115         if (flags & OREFLAG_ABSHEIGHT)
116                 in_range |= (nmin.Y >= -height_max && nmax.Y <= -height_min) << 1;
117         if (!in_range)
118                 return;
119
120         int ymin, ymax;
121         if (in_range & ORE_RANGE_MIRROR) {
122                 ymin = MYMAX(nmin.Y, -height_max);
123                 ymax = MYMIN(nmax.Y, -height_min);
124         } else {
125                 ymin = MYMAX(nmin.Y, height_min);
126                 ymax = MYMIN(nmax.Y, height_max);
127         }
128         if (clust_size >= ymax - ymin + 1)
129                 return;
130
131         nmin.Y = ymin;
132         nmax.Y = ymax;
133         generate(mg->vm, mg->seed, blockseed, nmin, nmax);
134 }
135
136
137 void OreScatter::generate(ManualMapVoxelManipulator *vm, int seed,
138                                                   u32 blockseed, v3s16 nmin, v3s16 nmax) {
139         PseudoRandom pr(blockseed);
140         MapNode n_ore(ore, 0, ore_param2);
141
142         int volume = (nmax.X - nmin.X + 1) *
143                                  (nmax.Y - nmin.Y + 1) *
144                                  (nmax.Z - nmin.Z + 1);
145         int csize     = clust_size;
146         int orechance = (csize * csize * csize) / clust_num_ores;
147         int nclusters = volume / clust_scarcity;
148
149         for (int i = 0; i != nclusters; i++) {
150                 int x0 = pr.range(nmin.X, nmax.X - csize + 1);
151                 int y0 = pr.range(nmin.Y, nmax.Y - csize + 1);
152                 int z0 = pr.range(nmin.Z, nmax.Z - csize + 1);
153  
154                 if (np && (NoisePerlin3D(np, x0, y0, z0, seed) < nthresh))
155                         continue;
156
157                 for (int z1 = 0; z1 != csize; z1++)
158                 for (int y1 = 0; y1 != csize; y1++)
159                 for (int x1 = 0; x1 != csize; x1++) {
160                         if (pr.range(1, orechance) != 1)
161                                 continue;
162
163                         u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1);
164                         if (vm->m_data[i].getContent() == wherein)
165                                 vm->m_data[i] = n_ore;
166                 }
167         }
168 }
169
170
171 void OreSheet::generate(ManualMapVoxelManipulator *vm, int seed,
172                                                 u32 blockseed, v3s16 nmin, v3s16 nmax) {
173         PseudoRandom pr(blockseed + 4234);
174         MapNode n_ore(ore, 0, ore_param2);
175
176         int max_height = clust_size;
177         int y_start = pr.range(nmin.Y, nmax.Y - max_height);
178
179         if (!noise) {
180                 int sx = nmax.X - nmin.X + 1;
181                 int sz = nmax.Z - nmin.Z + 1;
182                 noise = new Noise(np, 0, sx, sz);
183         }
184         noise->seed = seed + y_start;
185         noise->perlinMap2D(nmin.X, nmin.Z);
186
187         int index = 0;
188         for (int z = nmin.Z; z <= nmax.Z; z++)
189         for (int x = nmin.X; x <= nmax.X; x++) {
190                 float noiseval = noise->result[index++];
191                 if (noiseval < nthresh)
192                         continue;
193
194                 int height = max_height * (1. / pr.range(1, 3));
195                 int y0 = y_start + np->scale * noiseval; //pr.range(1, 3) - 1;
196                 int y1 = y0 + height;
197                 for (int y = y0; y != y1; y++) {
198                         u32 i = vm->m_area.index(x, y, z);
199                         if (!vm->m_area.contains(i))
200                                 continue;
201
202                         if (vm->m_data[i].getContent() == wherein)
203                                 vm->m_data[i] = n_ore;
204                 }
205         }
206 }
207
208
209 ///////////////////////////////////////////////////////////////////////////////
210
211
212 Decoration *createDecoration(DecorationType type) {
213         switch (type) {
214                 case DECO_SIMPLE:
215                         return new DecoSimple;
216                 case DECO_SCHEMATIC:
217                         return new DecoSchematic;
218                 //case DECO_LSYSTEM:
219                 //      return new DecoLSystem;
220                 default:
221                         return NULL;
222         }
223 }
224
225
226 Decoration::Decoration() {
227         mapseed    = 0;
228         np         = NULL;
229         fill_ratio = 0;
230         sidelen    = 1;
231 }
232
233
234 Decoration::~Decoration() {
235         delete np;
236 }
237
238
239 void Decoration::resolveNodeNames(INodeDefManager *ndef) {
240         this->ndef = ndef;
241         
242         if (c_place_on == CONTENT_IGNORE)
243                 c_place_on = ndef->getId(place_on_name);
244 }
245
246
247 void Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
248         PseudoRandom ps(blockseed + 53);
249         int carea_size = nmax.X - nmin.X + 1;
250
251         // Divide area into parts
252         if (carea_size % sidelen) {
253                 errorstream << "Decoration::placeDeco: chunk size is not divisible by "
254                         "sidelen; setting sidelen to " << carea_size << std::endl;
255                 sidelen = carea_size;
256         }
257         
258         s16 divlen = carea_size / sidelen;
259         int area = sidelen * sidelen;
260
261         for (s16 z0 = 0; z0 < divlen; z0++)
262         for (s16 x0 = 0; x0 < divlen; x0++) {
263                 v2s16 p2d_center( // Center position of part of division
264                         nmin.X + sidelen / 2 + sidelen * x0,
265                         nmin.Z + sidelen / 2 + sidelen * z0
266                 );
267                 v2s16 p2d_min( // Minimum edge of part of division
268                         nmin.X + sidelen * x0,
269                         nmin.Z + sidelen * z0
270                 );
271                 v2s16 p2d_max( // Maximum edge of part of division
272                         nmin.X + sidelen + sidelen * x0 - 1,
273                         nmin.Z + sidelen + sidelen * z0 - 1
274                 );
275
276                 // Amount of decorations
277                 float nval = np ?
278                         NoisePerlin2D(np, p2d_center.X, p2d_center.Y, mapseed) :
279                         fill_ratio;
280                 u32 deco_count = area * MYMAX(nval, 0.f);
281
282                 for (u32 i = 0; i < deco_count; i++) {
283                         s16 x = ps.range(p2d_min.X, p2d_max.X);
284                         s16 z = ps.range(p2d_min.Y, p2d_max.Y);
285
286                         int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X);
287                         
288                         s16 y = mg->heightmap ? 
289                                         mg->heightmap[mapindex] :
290                                         mg->findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
291                                         
292                         if (y < nmin.Y || y > nmax.Y)
293                                 continue;
294
295                         int height = getHeight();
296                         int max_y = nmax.Y;// + MAP_BLOCKSIZE - 1;
297                         if (y + 1 + height > max_y) {
298                                 continue;
299 #if 0
300                                 printf("Decoration at (%d %d %d) cut off\n", x, y, z);
301                                 //add to queue
302                                 JMutexAutoLock cutofflock(cutoff_mutex);
303                                 cutoffs.push_back(CutoffData(x, y, z, height));
304 #endif
305                         }
306
307                         if (mg->biomemap) {
308                                 std::set<u8>::iterator iter;
309                                 
310                                 if (biomes.size()) {
311                                         iter = biomes.find(mg->biomemap[mapindex]);
312                                         if (iter == biomes.end())
313                                                 continue;
314                                 }
315                         }
316
317                         generate(mg, &ps, max_y, v3s16(x, y, z));
318                 }
319         }
320 }
321
322
323 #if 0
324 void Decoration::placeCutoffs(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
325         PseudoRandom pr(blockseed + 53);
326         std::vector<CutoffData> handled_cutoffs;
327         
328         // Copy over the cutoffs we're interested in so we don't needlessly hold a lock
329         {
330                 JMutexAutoLock cutofflock(cutoff_mutex);
331                 for (std::list<CutoffData>::iterator i = cutoffs.begin();
332                         i != cutoffs.end(); ++i) {
333                         CutoffData cutoff = *i;
334                         v3s16 p    = cutoff.p;
335                         s16 height = cutoff.height;
336                         if (p.X < nmin.X || p.X > nmax.X ||
337                                 p.Z < nmin.Z || p.Z > nmax.Z)
338                                 continue;
339                         if (p.Y + height < nmin.Y || p.Y > nmax.Y)
340                                 continue;
341                         
342                         handled_cutoffs.push_back(cutoff);
343                 }
344         }
345         
346         // Generate the cutoffs
347         for (size_t i = 0; i != handled_cutoffs.size(); i++) {
348                 v3s16 p    = handled_cutoffs[i].p;
349                 s16 height = handled_cutoffs[i].height;
350                 
351                 if (p.Y + height > nmax.Y) {
352                         //printf("Decoration at (%d %d %d) cut off again!\n", p.X, p.Y, p.Z);
353                         cuttoffs.push_back(v3s16(p.X, p.Y, p.Z));
354                 }
355                 
356                 generate(mg, &pr, nmax.Y, nmin.Y - p.Y, v3s16(p.X, nmin.Y, p.Z));
357         }
358         
359         // Remove cutoffs that were handled from the cutoff list
360         {
361                 JMutexAutoLock cutofflock(cutoff_mutex);
362                 for (std::list<CutoffData>::iterator i = cutoffs.begin();
363                         i != cutoffs.end(); ++i) {
364                         
365                         for (size_t j = 0; j != handled_cutoffs.size(); j++) {
366                                 CutoffData coff = *i;
367                                 if (coff.p == handled_cutoffs[j].p)
368                                         i = cutoffs.erase(i);
369                         }
370                 }
371         }       
372 }
373 #endif
374
375
376 ///////////////////////////////////////////////////////////////////////////////
377
378
379 void DecoSimple::resolveNodeNames(INodeDefManager *ndef) {
380         Decoration::resolveNodeNames(ndef);
381         
382         if (c_deco == CONTENT_IGNORE) {
383                 c_deco = ndef->getId(deco_name);
384                 if (c_deco == CONTENT_IGNORE) {
385                         errorstream << "DecoSimple::resolveNodeNames: decoration node '"
386                                 << deco_name << "' not defined" << std::endl;
387                         c_deco = CONTENT_AIR;
388                 }
389         }
390         if (c_spawnby == CONTENT_IGNORE) {
391                 c_spawnby = ndef->getId(spawnby_name);
392                 if (c_spawnby == CONTENT_IGNORE) {
393                         errorstream << "DecoSimple::resolveNodeNames: spawnby node '"
394                                 << deco_name << "' not defined" << std::endl;
395                         nspawnby = -1;
396                         c_spawnby = CONTENT_AIR;
397                 }
398         }
399         
400         if (c_decolist.size())
401                 return;
402         
403         for (size_t i = 0; i != decolist_names.size(); i++) {           
404                 content_t c = ndef->getId(decolist_names[i]);
405                 if (c == CONTENT_IGNORE) {
406                         errorstream << "DecoSimple::resolveNodeNames: decolist node '"
407                                 << decolist_names[i] << "' not defined" << std::endl;
408                         c = CONTENT_AIR;
409                 }
410                 c_decolist.push_back(c);
411         }
412 }
413
414
415 void DecoSimple::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) {
416         ManualMapVoxelManipulator *vm = mg->vm;
417
418         u32 vi = vm->m_area.index(p);
419         if (vm->m_data[vi].getContent() != c_place_on &&
420                 c_place_on != CONTENT_IGNORE)
421                 return;
422                 
423         if (nspawnby != -1) {
424                 int nneighs = 0;
425                 v3s16 dirs[8] = { // a Moore neighborhood
426                         v3s16( 0, 0,  1),
427                         v3s16( 0, 0, -1),
428                         v3s16( 1, 0,  0),
429                         v3s16(-1, 0,  0),
430                         v3s16( 1, 0,  1),
431                         v3s16(-1, 0,  1),
432                         v3s16(-1, 0, -1),
433                         v3s16( 1, 0, -1)
434                 };
435                 
436                 for (int i = 0; i != 8; i++) {
437                         u32 index = vm->m_area.index(p + dirs[i]);
438                         if (vm->m_area.contains(index) &&
439                                 vm->m_data[index].getContent() == c_spawnby)
440                                 nneighs++;
441                 }
442                 
443                 if (nneighs < nspawnby)
444                         return;
445         }
446         
447         size_t ndecos = c_decolist.size();
448         content_t c_place = ndecos ? c_decolist[pr->range(0, ndecos - 1)] : c_deco;
449
450         s16 height = (deco_height_max > 0) ?
451                 pr->range(deco_height, deco_height_max) : deco_height;
452
453         height = MYMIN(height, max_y - p.Y);
454         
455         v3s16 em = vm->m_area.getExtent();
456         for (int i = 0; i < height; i++) {
457                 vm->m_area.add_y(em, vi, 1);
458                 
459                 content_t c = vm->m_data[vi].getContent();
460                 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
461                         break;
462                 
463                 vm->m_data[vi] = MapNode(c_place);
464         }
465 }
466
467
468 int DecoSimple::getHeight() {
469         return (deco_height_max > 0) ? deco_height_max : deco_height;
470 }
471
472
473 std::string DecoSimple::getName() {
474         return deco_name;
475 }
476
477
478 ///////////////////////////////////////////////////////////////////////////////
479
480
481 DecoSchematic::DecoSchematic() {
482         node_names = NULL;
483         schematic  = NULL;
484         flags      = 0;
485         size       = v3s16(0, 0, 0);
486 }
487
488
489 DecoSchematic::~DecoSchematic() {
490         delete node_names;
491         delete []schematic;
492 }
493
494
495 void DecoSchematic::resolveNodeNames(INodeDefManager *ndef) {
496         Decoration::resolveNodeNames(ndef);
497         
498         if (filename.empty())
499                 return;
500         
501         if (!node_names) {
502                 errorstream << "DecoSchematic::resolveNodeNames: node name list was "
503                         "not created" << std::endl;
504                 return;
505         }
506         
507         for (size_t i = 0; i != node_names->size(); i++) {
508                 content_t c = ndef->getId(node_names->at(i));
509                 if (c == CONTENT_IGNORE) {
510                         errorstream << "DecoSchematic::resolveNodeNames: node '"
511                                 << node_names->at(i) << "' not defined" << std::endl;
512                         c = CONTENT_AIR;
513                 }
514                 c_nodes.push_back(c);
515         }
516                 
517         for (int i = 0; i != size.X * size.Y * size.Z; i++)
518                 schematic[i].setContent(c_nodes[schematic[i].getContent()]);
519         
520         delete node_names;
521         node_names = NULL;
522 }
523
524
525 void DecoSchematic::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) {
526         ManualMapVoxelManipulator *vm = mg->vm;
527
528         if (flags & DECO_PLACE_CENTER_X)
529                 p.X -= (size.X + 1) / 2;
530         if (flags & DECO_PLACE_CENTER_Y)
531                 p.Y -= (size.Y + 1) / 2;
532         if (flags & DECO_PLACE_CENTER_Z)
533                 p.Z -= (size.Z + 1) / 2;
534                 
535         u32 vi = vm->m_area.index(p);
536         if (vm->m_data[vi].getContent() != c_place_on &&
537                 c_place_on != CONTENT_IGNORE)
538                 return;
539         
540         Rotation rot = (rotation == ROTATE_RAND) ?
541                 (Rotation)pr->range(ROTATE_0, ROTATE_270) : rotation;
542         
543         blitToVManip(p, vm, rot, false);
544 }
545
546
547 int DecoSchematic::getHeight() {
548         return size.Y;
549 }
550
551
552 std::string DecoSchematic::getName() {
553         return filename;
554 }
555
556
557 void DecoSchematic::blitToVManip(v3s16 p, ManualMapVoxelManipulator *vm,
558                                                                 Rotation rot, bool force_placement) {
559         int xstride = 1;
560         int ystride = size.X;
561         int zstride = size.X * size.Y;
562
563         s16 sx = size.X;
564         s16 sy = size.Y;
565         s16 sz = size.Z;
566
567         int i_start, i_step_x, i_step_z;
568         switch (rot) {
569                 case ROTATE_90:
570                         i_start  = sx - 1;
571                         i_step_x = zstride;
572                         i_step_z = -xstride;
573                         SWAP(s16, sx, sz);
574                         break;
575                 case ROTATE_180:
576                         i_start  = zstride * (sz - 1) + sx - 1;
577                         i_step_x = -xstride;
578                         i_step_z = -zstride;
579                         break;
580                 case ROTATE_270:
581                         i_start  = zstride * (sz - 1);
582                         i_step_x = -zstride;
583                         i_step_z = xstride;
584                         SWAP(s16, sx, sz);
585                         break;
586                 default:
587                         i_start  = 0;
588                         i_step_x = xstride;
589                         i_step_z = zstride;
590         }
591         
592         for (s16 z = 0; z != sz; z++)
593         for (s16 y = 0; y != sy; y++) {
594                 u32 i = z * i_step_z + y * ystride + i_start;
595                 for (s16 x = 0; x != sx; x++, i += i_step_x) {
596                         u32 vi = vm->m_area.index(p.X + x, p.Y + y, p.Z + z);
597                         if (!vm->m_area.contains(vi))
598                                 continue;
599                         
600                         if (schematic[i].getContent() == CONTENT_IGNORE)
601                                 continue;
602
603                         if (!force_placement) {
604                                 content_t c = vm->m_data[vi].getContent();
605                                 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
606                                         continue;
607                         }
608                         
609                         if (schematic[i].param1 && myrand_range(1, 256) > schematic[i].param1)
610                                 continue;
611                         
612                         vm->m_data[vi] = schematic[i];
613                         vm->m_data[vi].param1 = 0;
614                         
615                         if (rot)
616                                 vm->m_data[vi].rotateAlongYAxis(ndef, rot);
617                 }
618         }
619 }
620
621
622 void DecoSchematic::placeStructure(Map *map, v3s16 p) {
623         assert(schematic != NULL);
624         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
625
626         Rotation rot = (rotation == ROTATE_RAND) ?
627                 (Rotation)myrand_range(ROTATE_0, ROTATE_270) : rotation;
628         
629         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
630                                 v3s16(size.Z, size.Y, size.X) : size;
631
632         if (flags & DECO_PLACE_CENTER_X)
633                 p.X -= (s.X + 1) / 2;
634         if (flags & DECO_PLACE_CENTER_Y)
635                 p.Y -= (s.Y + 1) / 2;
636         if (flags & DECO_PLACE_CENTER_Z)
637                 p.Z -= (s.Z + 1) / 2;
638                 
639         v3s16 bp1 = getNodeBlockPos(p);
640         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
641         vm->initialEmerge(bp1, bp2);
642         
643         blitToVManip(p, vm, rot, true);
644         
645         std::map<v3s16, MapBlock *> lighting_modified_blocks;
646         std::map<v3s16, MapBlock *> modified_blocks;
647         vm->blitBackAll(&modified_blocks);
648         
649         // TODO: Optimize this by using Mapgen::calcLighting() instead
650         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
651         map->updateLighting(lighting_modified_blocks, modified_blocks);
652
653         MapEditEvent event;
654         event.type = MEET_OTHER;
655         for (std::map<v3s16, MapBlock *>::iterator
656                 it = modified_blocks.begin();
657                 it != modified_blocks.end(); ++it)
658                 event.modified_blocks.insert(it->first);
659                 
660         map->dispatchEvent(&event);
661 }
662
663
664 bool DecoSchematic::loadSchematicFile() {
665         std::ifstream is(filename.c_str(), std::ios_base::binary);
666
667         u32 signature = readU32(is);
668         if (signature != MTSCHEM_FILE_SIGNATURE) {
669                 errorstream << "loadSchematicFile: invalid schematic "
670                         "file" << std::endl;
671                 return false;
672         }
673         
674         u16 version = readU16(is);
675         if (version != 1) {
676                 errorstream << "loadSchematicFile: unsupported schematic "
677                         "file version" << std::endl;
678                 return false;
679         }
680
681         size = readV3S16(is);
682         int nodecount = size.X * size.Y * size.Z;
683         
684         u16 nidmapcount = readU16(is);
685         
686         node_names = new std::vector<std::string>;
687         for (int i = 0; i != nidmapcount; i++) {
688                 std::string name = deSerializeString(is);
689                 node_names->push_back(name);
690         }
691
692         delete schematic;
693         schematic = new MapNode[nodecount];
694         MapNode::deSerializeBulk(is, SER_FMT_VER_HIGHEST_READ, schematic,
695                                 nodecount, 2, 2, true);
696                                 
697         return true;
698 }
699
700
701 /*
702         Minetest Schematic File Format
703
704         All values are stored in big-endian byte order.
705         [u32] signature: 'MTSM'
706         [u16] version: 1
707         [u16] size X
708         [u16] size Y
709         [u16] size Z
710         [Name-ID table] Name ID Mapping Table
711                 [u16] name-id count
712                 For each name-id mapping:
713                         [u16] name length
714                         [u8[]] name
715         ZLib deflated {
716         For each node in schematic:  (for z, y, x)
717                 [u16] content
718         For each node in schematic:
719                 [u8] probability of occurance (param1)
720         For each node in schematic:
721                 [u8] param2
722         }
723 */
724 void DecoSchematic::saveSchematicFile(INodeDefManager *ndef) {
725         std::ofstream os(filename.c_str(), std::ios_base::binary);
726
727         writeU32(os, MTSCHEM_FILE_SIGNATURE); // signature
728         writeU16(os, 1);      // version
729         writeV3S16(os, size); // schematic size
730         
731         std::vector<content_t> usednodes;
732         int nodecount = size.X * size.Y * size.Z;
733         build_nnlist_and_update_ids(schematic, nodecount, &usednodes);
734         
735         u16 numids = usednodes.size();
736         writeU16(os, numids); // name count
737         for (int i = 0; i != numids; i++)
738                 os << serializeString(ndef->get(usednodes[i]).name); // node names
739                 
740         // compressed bulk node data
741         MapNode::serializeBulk(os, SER_FMT_VER_HIGHEST_WRITE, schematic,
742                                 nodecount, 2, 2, true);
743 }
744
745
746 void build_nnlist_and_update_ids(MapNode *nodes, u32 nodecount,
747                                                 std::vector<content_t> *usednodes) {
748         std::map<content_t, content_t> nodeidmap;
749         content_t numids = 0;
750         
751         for (u32 i = 0; i != nodecount; i++) {
752                 content_t id;
753                 content_t c = nodes[i].getContent();
754
755                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
756                 if (it == nodeidmap.end()) {
757                         id = numids;
758                         numids++;
759
760                         usednodes->push_back(c);
761                         nodeidmap.insert(std::make_pair(c, id));
762                 } else {
763                         id = it->second;
764                 }
765                 nodes[i].setContent(id);
766         }
767 }
768
769
770 bool DecoSchematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) {
771         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
772
773         v3s16 bp1 = getNodeBlockPos(p1);
774         v3s16 bp2 = getNodeBlockPos(p2);
775         vm->initialEmerge(bp1, bp2);
776         
777         size = p2 - p1 + 1;
778         schematic = new MapNode[size.X * size.Y * size.Z];
779         
780         u32 i = 0;
781         for (s16 z = p1.Z; z <= p2.Z; z++)
782         for (s16 y = p1.Y; y <= p2.Y; y++) {
783                 u32 vi = vm->m_area.index(p1.X, y, z);
784                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
785                         schematic[i] = vm->m_data[vi];
786                         schematic[i].param1 = 0;
787                 }
788         }
789
790         delete vm;
791         return true;
792 }
793
794
795 void DecoSchematic::applyProbabilities(std::vector<std::pair<v3s16, s16> > *plist, v3s16 p0) {
796         for (size_t i = 0; i != plist->size(); i++) {
797                 v3s16 p = (*plist)[i].first - p0;
798                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
799                 if (index < size.Z * size.Y * size.X) {
800                         s16 prob = (*plist)[i].second;
801                         if (prob != -1)
802                                 schematic[index].param1 = prob;
803                         else
804                                 schematic[index].setContent(CONTENT_IGNORE);
805                 }
806         }
807 }
808
809
810 ///////////////////////////////////////////////////////////////////////////////
811
812
813 Mapgen::Mapgen() {
814         seed        = 0;
815         water_level = 0;
816         generating  = false;
817         id          = -1;
818         vm          = NULL;
819         ndef        = NULL;
820         heightmap   = NULL;
821         biomemap    = NULL;
822 }
823
824
825 // Returns Y one under area minimum if not found
826 s16 Mapgen::findGroundLevelFull(v2s16 p2d) {
827         v3s16 em = vm->m_area.getExtent();
828         s16 y_nodes_max = vm->m_area.MaxEdge.Y;
829         s16 y_nodes_min = vm->m_area.MinEdge.Y;
830         u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y);
831         s16 y;
832         
833         for (y = y_nodes_max; y >= y_nodes_min; y--) {
834                 MapNode &n = vm->m_data[i];
835                 if (ndef->get(n).walkable)
836                         break;
837
838                 vm->m_area.add_y(em, i, -1);
839         }
840         return (y >= y_nodes_min) ? y : y_nodes_min - 1;
841 }
842
843
844 s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) {
845         v3s16 em = vm->m_area.getExtent();
846         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
847         s16 y;
848         
849         for (y = ymax; y >= ymin; y--) {
850                 MapNode &n = vm->m_data[i];
851                 if (ndef->get(n).walkable)
852                         break;
853
854                 vm->m_area.add_y(em, i, -1);
855         }
856         return y;
857 }
858
859
860 void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) {
861         if (!heightmap)
862                 return;
863         
864         //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
865         int index = 0;
866         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
867                 for (s16 x = nmin.X; x <= nmax.X; x++, index++) {
868                         s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
869
870                         // if the values found are out of range, trust the old heightmap
871                         if (y == nmax.Y && heightmap[index] > nmax.Y)
872                                 continue;
873                         if (y == nmin.Y - 1 && heightmap[index] < nmin.Y)
874                                 continue;
875                                 
876                         heightmap[index] = y;
877                 }
878         }
879         //printf("updateHeightmap: %dus\n", t.stop());
880 }
881
882
883 void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax) {
884         bool isliquid, wasliquid, rare;
885         v3s16 em  = vm->m_area.getExtent();
886         rare = g_settings->getBool("liquid_finite");
887         int rarecnt = 0;
888
889         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
890                 for (s16 x = nmin.X; x <= nmax.X; x++) {
891                         wasliquid = true;
892
893                         u32 i = vm->m_area.index(x, nmax.Y, z);
894                         for (s16 y = nmax.Y; y >= nmin.Y; y--) {
895                                 isliquid = ndef->get(vm->m_data[i]).isLiquid();
896
897                                 // there was a change between liquid and nonliquid, add to queue. no need to add every with liquid_finite
898                                 if (isliquid != wasliquid && (!rare || !(rarecnt++ % 36)))
899                                         trans_liquid->push_back(v3s16(x, y, z));
900
901                                 wasliquid = isliquid;
902                                 vm->m_area.add_y(em, i, -1);
903                         }
904                 }
905         }
906 }
907
908
909 void Mapgen::setLighting(v3s16 nmin, v3s16 nmax, u8 light) {
910         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
911         VoxelArea a(nmin, nmax);
912
913         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
914                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
915                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
916                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
917                                 vm->m_data[i].param1 = light;
918                 }
919         }
920 }
921
922
923 void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light) {
924         if (light <= 1 || !a.contains(p))
925                 return;
926
927         u32 vi = vm->m_area.index(p);
928         MapNode &nn = vm->m_data[vi];
929
930         light--;
931         // should probably compare masked, but doesn't seem to make a difference
932         if (light <= nn.param1 || !ndef->get(nn).light_propagates)
933                 return;
934
935         nn.param1 = light;
936
937         lightSpread(a, p + v3s16(0, 0, 1), light);
938         lightSpread(a, p + v3s16(0, 1, 0), light);
939         lightSpread(a, p + v3s16(1, 0, 0), light);
940         lightSpread(a, p - v3s16(0, 0, 1), light);
941         lightSpread(a, p - v3s16(0, 1, 0), light);
942         lightSpread(a, p - v3s16(1, 0, 0), light);
943 }
944
945
946 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax) {
947         VoxelArea a(nmin, nmax);
948         bool block_is_underground = (water_level >= nmax.Y);
949
950         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
951         //TimeTaker t("updateLighting");
952
953         // first, send vertical rays of sunshine downward
954         v3s16 em = vm->m_area.getExtent();
955         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
956                 for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
957                         // see if we can get a light value from the overtop
958                         u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
959                         if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
960                                 if (block_is_underground)
961                                         continue;
962                         } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN) {
963                                 continue;
964                         }
965                         vm->m_area.add_y(em, i, -1);
966  
967                         for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
968                                 MapNode &n = vm->m_data[i];
969                                 if (!ndef->get(n).sunlight_propagates)
970                                         break;
971                                 n.param1 = LIGHT_SUN;
972                                 vm->m_area.add_y(em, i, -1);
973                         }
974                 }
975         }
976
977         // now spread the sunlight and light up any sources
978         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
979                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
980                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
981                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
982                                 MapNode &n = vm->m_data[i];
983                                 if (n.getContent() == CONTENT_IGNORE ||
984                                         !ndef->get(n).light_propagates)
985                                         continue;
986
987                                 u8 light_produced = ndef->get(n).light_source & 0x0F;
988                                 if (light_produced)
989                                         n.param1 = light_produced;
990
991                                 u8 light = n.param1 & 0x0F;
992                                 if (light) {
993                                         lightSpread(a, v3s16(x,     y,     z + 1), light - 1);
994                                         lightSpread(a, v3s16(x,     y + 1, z    ), light - 1);
995                                         lightSpread(a, v3s16(x + 1, y,     z    ), light - 1);
996                                         lightSpread(a, v3s16(x,     y,     z - 1), light - 1);
997                                         lightSpread(a, v3s16(x,     y - 1, z    ), light - 1);
998                                         lightSpread(a, v3s16(x - 1, y,     z    ), light - 1);
999                                 }
1000                         }
1001                 }
1002         }
1003
1004         //printf("updateLighting: %dms\n", t.stop());
1005 }
1006
1007
1008 void Mapgen::calcLightingOld(v3s16 nmin, v3s16 nmax) {
1009         enum LightBank banks[2] = {LIGHTBANK_DAY, LIGHTBANK_NIGHT};
1010         VoxelArea a(nmin, nmax);
1011         bool block_is_underground = (water_level > nmax.Y);
1012         bool sunlight = !block_is_underground;
1013
1014         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
1015
1016         for (int i = 0; i < 2; i++) {
1017                 enum LightBank bank = banks[i];
1018                 std::set<v3s16> light_sources;
1019                 std::map<v3s16, u8> unlight_from;
1020
1021                 voxalgo::clearLightAndCollectSources(*vm, a, bank, ndef,
1022                                                                                          light_sources, unlight_from);
1023                 voxalgo::propagateSunlight(*vm, a, sunlight, light_sources, ndef);
1024
1025                 vm->unspreadLight(bank, unlight_from, light_sources, ndef);
1026                 vm->spreadLight(bank, light_sources, ndef);
1027         }
1028 }
1029  
1030  
1031 //////////////////////// Mapgen V6 parameter read/write
1032  
1033 bool MapgenV6Params::readParams(Settings *settings) {
1034         freq_desert = settings->getFloat("mgv6_freq_desert");
1035         freq_beach  = settings->getFloat("mgv6_freq_beach");
1036
1037         bool success = 
1038                 settings->getNoiseParams("mgv6_np_terrain_base",   np_terrain_base)   &&
1039                 settings->getNoiseParams("mgv6_np_terrain_higher", np_terrain_higher) &&
1040                 settings->getNoiseParams("mgv6_np_steepness",      np_steepness)      &&
1041                 settings->getNoiseParams("mgv6_np_height_select",  np_height_select)  &&
1042                 settings->getNoiseParams("mgv6_np_mud",            np_mud)            &&
1043                 settings->getNoiseParams("mgv6_np_beach",          np_beach)          &&
1044                 settings->getNoiseParams("mgv6_np_biome",          np_biome)          &&
1045                 settings->getNoiseParams("mgv6_np_cave",           np_cave)           &&
1046                 settings->getNoiseParams("mgv6_np_humidity",       np_humidity)       &&
1047                 settings->getNoiseParams("mgv6_np_trees",          np_trees)          &&
1048                 settings->getNoiseParams("mgv6_np_apple_trees",    np_apple_trees);
1049         return success;
1050 }
1051  
1052  
1053 void MapgenV6Params::writeParams(Settings *settings) {
1054         settings->setFloat("mgv6_freq_desert", freq_desert);
1055         settings->setFloat("mgv6_freq_beach",  freq_beach);
1056  
1057         settings->setNoiseParams("mgv6_np_terrain_base",   np_terrain_base);
1058         settings->setNoiseParams("mgv6_np_terrain_higher", np_terrain_higher);
1059         settings->setNoiseParams("mgv6_np_steepness",      np_steepness);
1060         settings->setNoiseParams("mgv6_np_height_select",  np_height_select);
1061         settings->setNoiseParams("mgv6_np_mud",            np_mud);
1062         settings->setNoiseParams("mgv6_np_beach",          np_beach);
1063         settings->setNoiseParams("mgv6_np_biome",          np_biome);
1064         settings->setNoiseParams("mgv6_np_cave",           np_cave);
1065         settings->setNoiseParams("mgv6_np_humidity",       np_humidity);
1066         settings->setNoiseParams("mgv6_np_trees",          np_trees);
1067         settings->setNoiseParams("mgv6_np_apple_trees",    np_apple_trees);
1068 }
1069
1070
1071 bool MapgenV7Params::readParams(Settings *settings) {
1072         bool success = 
1073                 settings->getNoiseParams("mgv7_np_terrain_base",    np_terrain_base)    &&
1074                 settings->getNoiseParams("mgv7_np_terrain_alt",     np_terrain_alt)     &&
1075                 settings->getNoiseParams("mgv7_np_terrain_persist", np_terrain_persist) &&
1076                 settings->getNoiseParams("mgv7_np_height_select",   np_height_select)   &&
1077                 settings->getNoiseParams("mgv7_np_filler_depth",    np_filler_depth)    &&
1078                 settings->getNoiseParams("mgv7_np_mount_height",    np_mount_height)    &&
1079                 settings->getNoiseParams("mgv7_np_ridge_uwater",    np_ridge_uwater)    &&
1080                 settings->getNoiseParams("mgv7_np_mountain",        np_mountain)        &&
1081                 settings->getNoiseParams("mgv7_np_ridge",           np_ridge);
1082         return success;
1083 }
1084
1085
1086 void MapgenV7Params::writeParams(Settings *settings) {
1087         settings->setNoiseParams("mgv7_np_terrain_base",    np_terrain_base);
1088         settings->setNoiseParams("mgv7_np_terrain_alt",     np_terrain_alt);
1089         settings->setNoiseParams("mgv7_np_terrain_persist", np_terrain_persist);
1090         settings->setNoiseParams("mgv7_np_height_select",   np_height_select);
1091         settings->setNoiseParams("mgv7_np_filler_depth",    np_filler_depth);
1092         settings->setNoiseParams("mgv7_np_mount_height",    np_mount_height);
1093         settings->setNoiseParams("mgv7_np_ridge_uwater",    np_ridge_uwater);
1094         settings->setNoiseParams("mgv7_np_mountain",        np_mountain);
1095         settings->setNoiseParams("mgv7_np_ridge",           np_ridge);
1096 }
1097
1098
1099 /////////////////////////////////// legacy static functions for farmesh
1100
1101 s16 Mapgen::find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision) {
1102         //just need to return something
1103         s16 level = 5;
1104         return level;
1105 }
1106
1107
1108 bool Mapgen::get_have_beach(u64 seed, v2s16 p2d) {
1109         double sandnoise = noise2d_perlin(
1110                                 0.2+(float)p2d.X/250, 0.7+(float)p2d.Y/250,
1111                                 seed+59420, 3, 0.50);
1112  
1113         return (sandnoise > 0.15);
1114 }
1115
1116
1117 double Mapgen::tree_amount_2d(u64 seed, v2s16 p) {
1118         double noise = noise2d_perlin(
1119                         0.5+(float)p.X/125, 0.5+(float)p.Y/125,
1120                         seed+2, 4, 0.66);
1121         double zeroval = -0.39;
1122         if(noise < zeroval)
1123                 return 0;
1124         else
1125                 return 0.04 * (noise-zeroval) / (1.0-zeroval);
1126 }