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