Decoration: Add schematic rotation support
[oweals/minetest.git] / src / mapgen.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "mapgen.h"
21 #include "voxel.h"
22 #include "noise.h"
23 #include "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         if (c_place_on == CONTENT_IGNORE)
241                 c_place_on = ndef->getId(place_on_name);
242 }
243
244
245 void Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
246         PseudoRandom ps(blockseed + 53);
247         int carea_size = nmax.X - nmin.X + 1;
248
249         // Divide area into parts
250         if (carea_size % sidelen) {
251                 errorstream << "Decoration::placeDeco: chunk size is not divisible by "
252                         "sidelen; setting sidelen to " << carea_size << std::endl;
253                 sidelen = carea_size;
254         }
255         
256         s16 divlen = carea_size / sidelen;
257         int area = sidelen * sidelen;
258
259         for (s16 z0 = 0; z0 < divlen; z0++)
260         for (s16 x0 = 0; x0 < divlen; x0++) {
261                 v2s16 p2d_center( // Center position of part of division
262                         nmin.X + sidelen / 2 + sidelen * x0,
263                         nmin.Z + sidelen / 2 + sidelen * z0
264                 );
265                 v2s16 p2d_min( // Minimum edge of part of division
266                         nmin.X + sidelen * x0,
267                         nmin.Z + sidelen * z0
268                 );
269                 v2s16 p2d_max( // Maximum edge of part of division
270                         nmin.X + sidelen + sidelen * x0 - 1,
271                         nmin.Z + sidelen + sidelen * z0 - 1
272                 );
273
274                 // Amount of decorations
275                 float nval = np ?
276                         NoisePerlin2D(np, p2d_center.X, p2d_center.Y, mapseed) :
277                         fill_ratio;
278                 u32 deco_count = area * MYMAX(nval, 0.f);
279
280                 for (u32 i = 0; i < deco_count; i++) {
281                         s16 x = ps.range(p2d_min.X, p2d_max.X);
282                         s16 z = ps.range(p2d_min.Y, p2d_max.Y);
283
284                         int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X);
285                         
286                         s16 y = mg->heightmap ? 
287                                         mg->heightmap[mapindex] :
288                                         mg->findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
289                                         
290                         if (y < nmin.Y || y > nmax.Y)
291                                 continue;
292
293                         int height = getHeight();
294                         int max_y = nmax.Y + MAP_BLOCKSIZE;
295                         if (y + 1 + height > max_y) {
296                                 continue;
297 #if 0
298                                 printf("Decoration at (%d %d %d) cut off\n", x, y, z);
299                                 //add to queue
300                                 JMutexAutoLock cutofflock(cutoff_mutex);
301                                 cutoffs.push_back(CutoffData(x, y, z, height));
302 #endif
303                         }
304
305                         if (mg->biomemap) {
306                                 std::set<u8>::iterator iter;
307                                 
308                                 if (biomes.size()) {
309                                         iter = biomes.find(mg->biomemap[mapindex]);
310                                         if (iter == biomes.end())
311                                                 continue;
312                                 }
313                         }
314
315                         generate(mg, &ps, max_y, v3s16(x, y, z));
316                 }
317         }
318 }
319
320
321 #if 0
322 void Decoration::placeCutoffs(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
323         PseudoRandom pr(blockseed + 53);
324         std::vector<CutoffData> handled_cutoffs;
325         
326         // Copy over the cutoffs we're interested in so we don't needlessly hold a lock
327         {
328                 JMutexAutoLock cutofflock(cutoff_mutex);
329                 for (std::list<CutoffData>::iterator i = cutoffs.begin();
330                         i != cutoffs.end(); ++i) {
331                         CutoffData cutoff = *i;
332                         v3s16 p    = cutoff.p;
333                         s16 height = cutoff.height;
334                         if (p.X < nmin.X || p.X > nmax.X ||
335                                 p.Z < nmin.Z || p.Z > nmax.Z)
336                                 continue;
337                         if (p.Y + height < nmin.Y || p.Y > nmax.Y)
338                                 continue;
339                         
340                         handled_cutoffs.push_back(cutoff);
341                 }
342         }
343         
344         // Generate the cutoffs
345         for (size_t i = 0; i != handled_cutoffs.size(); i++) {
346                 v3s16 p    = handled_cutoffs[i].p;
347                 s16 height = handled_cutoffs[i].height;
348                 
349                 if (p.Y + height > nmax.Y) {
350                         //printf("Decoration at (%d %d %d) cut off again!\n", p.X, p.Y, p.Z);
351                         cuttoffs.push_back(v3s16(p.X, p.Y, p.Z));
352                 }
353                 
354                 generate(mg, &pr, nmax.Y, nmin.Y - p.Y, v3s16(p.X, nmin.Y, p.Z));
355         }
356         
357         // Remove cutoffs that were handled from the cutoff list
358         {
359                 JMutexAutoLock cutofflock(cutoff_mutex);
360                 for (std::list<CutoffData>::iterator i = cutoffs.begin();
361                         i != cutoffs.end(); ++i) {
362                         
363                         for (size_t j = 0; j != handled_cutoffs.size(); j++) {
364                                 CutoffData coff = *i;
365                                 if (coff.p == handled_cutoffs[j].p)
366                                         i = cutoffs.erase(i);
367                         }
368                 }
369         }       
370 }
371 #endif
372
373
374 ///////////////////////////////////////////////////////////////////////////////
375
376
377 void DecoSimple::resolveNodeNames(INodeDefManager *ndef) {
378         Decoration::resolveNodeNames(ndef);
379         
380         if (c_deco == CONTENT_IGNORE) {
381                 c_deco = ndef->getId(deco_name);
382                 if (c_deco == CONTENT_IGNORE) {
383                         errorstream << "DecoSimple::resolveNodeNames: decoration node '"
384                                 << deco_name << "' not defined" << std::endl;
385                         c_deco = CONTENT_AIR;
386                 }
387         }
388         if (c_spawnby == CONTENT_IGNORE) {
389                 c_spawnby = ndef->getId(spawnby_name);
390                 if (c_spawnby == CONTENT_IGNORE) {
391                         errorstream << "DecoSimple::resolveNodeNames: spawnby node '"
392                                 << deco_name << "' not defined" << std::endl;
393                         nspawnby = -1;
394                         c_spawnby = CONTENT_AIR;
395                 }
396         }
397         
398         if (c_decolist.size())
399                 return;
400         
401         for (size_t i = 0; i != decolist_names.size(); i++) {           
402                 content_t c = ndef->getId(decolist_names[i]);
403                 if (c == CONTENT_IGNORE) {
404                         errorstream << "DecoSimple::resolveNodeNames: decolist node '"
405                                 << decolist_names[i] << "' not defined" << std::endl;
406                         c = CONTENT_AIR;
407                 }
408                 c_decolist.push_back(c);
409         }
410 }
411
412
413 void DecoSimple::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) {
414         ManualMapVoxelManipulator *vm = mg->vm;
415
416         u32 vi = vm->m_area.index(p);
417         if (vm->m_data[vi].getContent() != c_place_on &&
418                 c_place_on != CONTENT_IGNORE)
419                 return;
420                 
421         if (nspawnby != -1) {
422                 int nneighs = 0;
423                 v3s16 dirs[8] = { // a Moore neighborhood
424                         v3s16( 0, 0,  1),
425                         v3s16( 0, 0, -1),
426                         v3s16( 1, 0,  0),
427                         v3s16(-1, 0,  0),
428                         v3s16( 1, 0,  1),
429                         v3s16(-1, 0,  1),
430                         v3s16(-1, 0, -1),
431                         v3s16( 1, 0, -1)
432                 };
433                 
434                 for (int i = 0; i != 8; i++) {
435                         u32 index = vm->m_area.index(p + dirs[i]);
436                         if (vm->m_area.contains(index) &&
437                                 vm->m_data[index].getContent() == c_spawnby)
438                                 nneighs++;
439                 }
440                 
441                 if (nneighs < nspawnby)
442                         return;
443         }
444         
445         size_t ndecos = c_decolist.size();
446         content_t c_place = ndecos ? c_decolist[pr->range(0, ndecos - 1)] : c_deco;
447
448         s16 height = (deco_height_max > 0) ?
449                 pr->range(deco_height, deco_height_max) : deco_height;
450
451         height = MYMIN(height, max_y - p.Y);
452         
453         v3s16 em = vm->m_area.getExtent();
454         for (int i = 0; i < height; i++) {
455                 vm->m_area.add_y(em, vi, 1);
456                 
457                 content_t c = vm->m_data[vi].getContent();
458                 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
459                         break;
460                 
461                 vm->m_data[vi] = MapNode(c_place);
462         }
463 }
464
465
466 int DecoSimple::getHeight() {
467         return (deco_height_max > 0) ? deco_height_max : deco_height;
468 }
469
470
471 std::string DecoSimple::getName() {
472         return deco_name;
473 }
474
475
476 ///////////////////////////////////////////////////////////////////////////////
477
478
479 DecoSchematic::DecoSchematic() {
480         node_names = NULL;
481         schematic  = NULL;
482         flags      = 0;
483         size       = v3s16(0, 0, 0);
484 }
485
486
487 DecoSchematic::~DecoSchematic() {
488         delete node_names;
489         delete []schematic;
490 }
491
492
493 void DecoSchematic::resolveNodeNames(INodeDefManager *ndef) {
494         Decoration::resolveNodeNames(ndef);
495         
496         if (filename.empty())
497                 return;
498         
499         if (!node_names) {
500                 errorstream << "DecoSchematic::resolveNodeNames: node name list was "
501                         "not created" << std::endl;
502                 return;
503         }
504         
505         for (size_t i = 0; i != node_names->size(); i++) {
506                 content_t c = ndef->getId(node_names->at(i));
507                 if (c == CONTENT_IGNORE) {
508                         errorstream << "DecoSchematic::resolveNodeNames: node '"
509                                 << node_names->at(i) << "' not defined" << std::endl;
510                         c = CONTENT_AIR;
511                 }
512                 c_nodes.push_back(c);
513         }
514                 
515         for (int i = 0; i != size.X * size.Y * size.Z; i++)
516                 schematic[i].setContent(c_nodes[schematic[i].getContent()]);
517         
518         delete node_names;
519         node_names = NULL;
520 }
521
522
523 void DecoSchematic::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) {
524         ManualMapVoxelManipulator *vm = mg->vm;
525
526         if (flags & DECO_PLACE_CENTER_X)
527                 p.X -= (size.X + 1) / 2;
528         if (flags & DECO_PLACE_CENTER_Y)
529                 p.Y -= (size.Y + 1) / 2;
530         if (flags & DECO_PLACE_CENTER_Z)
531                 p.Z -= (size.Z + 1) / 2;
532                 
533         u32 vi = vm->m_area.index(p);
534         if (vm->m_data[vi].getContent() != c_place_on &&
535                 c_place_on != CONTENT_IGNORE)
536                 return;
537         
538         Rotation rot = (rotation == ROTATE_RAND) ?
539                 (Rotation)pr->range(ROTATE_0, ROTATE_270) : rotation;
540         
541         blitToVManip(p, vm, rot, false);
542 }
543
544
545 int DecoSchematic::getHeight() {
546         return size.Y;
547 }
548
549
550 std::string DecoSchematic::getName() {
551         return filename;
552 }
553
554
555 void DecoSchematic::blitToVManip(v3s16 p, ManualMapVoxelManipulator *vm,
556                                                                 int rot, bool force_placement) {
557         int xstride = 1;
558         int ystride = size.X;
559         int zstride = size.X * size.Y;
560
561         s16 sx = size.X;
562         s16 sy = size.Y;
563         s16 sz = size.Z;
564
565         int i_start, i_step_x, i_step_z;
566         switch (rot) {
567                 case ROTATE_90:
568                         i_start  = sx - 1;
569                         i_step_x = zstride;
570                         i_step_z = -xstride;
571                         SWAP(s16, sx, sz);
572                         break;
573                 case ROTATE_180:
574                         i_start  = zstride * (sz - 1) + sx - 1;
575                         i_step_x = -xstride;
576                         i_step_z = -zstride;
577                         break;
578                 case ROTATE_270:
579                         i_start  = zstride * (sz - 1);
580                         i_step_x = -zstride;
581                         i_step_z = xstride;
582                         SWAP(s16, sx, sz);
583                         break;
584                 default:
585                         i_start  = 0;
586                         i_step_x = xstride;
587                         i_step_z = zstride;
588         }
589         
590         for (s16 z = 0; z != sz; z++)
591         for (s16 y = 0; y != sy; y++) {
592                 u32 i = z * i_step_z + y * ystride + i_start;
593                 for (s16 x = 0; x != sx; x++, i += i_step_x) {
594                         u32 vi = vm->m_area.index(p.X + x, p.Y + y, p.Z + z);
595                         if (!vm->m_area.contains(vi))
596                                 continue;
597                                 
598                         if (schematic[i].getContent() == CONTENT_IGNORE)
599                                 continue;
600
601                         if (!force_placement) {
602                                 content_t c = vm->m_data[vi].getContent();
603                                 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
604                                         continue;
605                         }
606                         
607                         if (schematic[i].param1 && myrand_range(1, 256) > schematic[i].param1)
608                                 continue;
609                         
610                         vm->m_data[vi] = schematic[i];
611                         vm->m_data[vi].param1 = 0;
612                 }
613         }
614 }
615
616
617 void DecoSchematic::placeStructure(Map *map, v3s16 p) {
618         assert(schematic != NULL);
619         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
620
621         Rotation rot = (rotation == ROTATE_RAND) ?
622                 (Rotation)myrand_range(ROTATE_0, ROTATE_270) : rotation;
623         
624         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
625                                 v3s16(size.Z, size.Y, size.X) : size;
626
627         if (flags & DECO_PLACE_CENTER_X)
628                 p.X -= (s.X + 1) / 2;
629         if (flags & DECO_PLACE_CENTER_Y)
630                 p.Y -= (s.Y + 1) / 2;
631         if (flags & DECO_PLACE_CENTER_Z)
632                 p.Z -= (s.Z + 1) / 2;
633                 
634         v3s16 bp1 = getNodeBlockPos(p);
635         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
636         vm->initialEmerge(bp1, bp2);
637         
638         blitToVManip(p, vm, rot, true);
639         
640         std::map<v3s16, MapBlock *> lighting_modified_blocks;
641         std::map<v3s16, MapBlock *> modified_blocks;
642         vm->blitBackAll(&modified_blocks);
643         
644         // TODO: Optimize this by using Mapgen::calcLighting() instead
645         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
646         map->updateLighting(lighting_modified_blocks, modified_blocks);
647
648         MapEditEvent event;
649         event.type = MEET_OTHER;
650         for (std::map<v3s16, MapBlock *>::iterator
651                 it = modified_blocks.begin();
652                 it != modified_blocks.end(); ++it)
653                 event.modified_blocks.insert(it->first);
654                 
655         map->dispatchEvent(&event);
656 }
657
658
659 bool DecoSchematic::loadSchematicFile() {
660         std::ifstream is(filename.c_str(), std::ios_base::binary);
661
662         u32 signature = readU32(is);
663         if (signature != 'MTSM') {
664                 errorstream << "loadSchematicFile: invalid schematic "
665                         "file" << std::endl;
666                 return false;
667         }
668         
669         u16 version = readU16(is);
670         if (version != 1) {
671                 errorstream << "loadSchematicFile: unsupported schematic "
672                         "file version" << std::endl;
673                 return false;
674         }
675
676         size = readV3S16(is);
677         int nodecount = size.X * size.Y * size.Z;
678         
679         u16 nidmapcount = readU16(is);
680         
681         node_names = new std::vector<std::string>;
682         for (int i = 0; i != nidmapcount; i++) {
683                 std::string name = deSerializeString(is);
684                 node_names->push_back(name);
685         }
686
687         delete schematic;
688         schematic = new MapNode[nodecount];
689         MapNode::deSerializeBulk(is, SER_FMT_VER_HIGHEST, schematic,
690                                 nodecount, 2, 2, true);
691                                 
692         return true;
693 }
694
695
696 /*
697         Minetest Schematic File Format
698
699         All values are stored in big-endian byte order.
700         [u32] signature: 'MTSM'
701         [u16] version: 1
702         [u16] size X
703         [u16] size Y
704         [u16] size Z
705         [Name-ID table] Name ID Mapping Table
706                 [u16] name-id count
707                 For each name-id mapping:
708                         [u16] name length
709                         [u8[]] name
710         ZLib deflated {
711         For each node in schematic:  (for z, y, x)
712                 [u16] content
713         For each node in schematic:
714                 [u8] probability of occurance (param1)
715         For each node in schematic:
716                 [u8] param2
717         }
718 */
719 void DecoSchematic::saveSchematicFile(INodeDefManager *ndef) {
720         std::ofstream os(filename.c_str(), std::ios_base::binary);
721
722         writeU32(os, 'MTSM'); // signature
723         writeU16(os, 1);      // version
724         writeV3S16(os, size); // schematic size
725         
726         std::vector<content_t> usednodes;
727         int nodecount = size.X * size.Y * size.Z;
728         build_nnlist_and_update_ids(schematic, nodecount, &usednodes);
729         
730         u16 numids = usednodes.size();
731         writeU16(os, numids); // name count
732         for (int i = 0; i != numids; i++)
733                 os << serializeString(ndef->get(usednodes[i]).name); // node names
734                 
735         // compressed bulk node data
736         MapNode::serializeBulk(os, SER_FMT_VER_HIGHEST, schematic,
737                                 nodecount, 2, 2, true);
738 }
739
740
741 void build_nnlist_and_update_ids(MapNode *nodes, u32 nodecount,
742                                                 std::vector<content_t> *usednodes) {
743         std::map<content_t, content_t> nodeidmap;
744         content_t numids = 0;
745         
746         for (u32 i = 0; i != nodecount; i++) {
747                 content_t id;
748                 content_t c = nodes[i].getContent();
749
750                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
751                 if (it == nodeidmap.end()) {
752                         id = numids;
753                         numids++;
754
755                         usednodes->push_back(c);
756                         nodeidmap.insert(std::make_pair(c, id));
757                 } else {
758                         id = it->second;
759                 }
760                 nodes[i].setContent(id);
761         }
762 }
763
764
765 bool DecoSchematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) {
766         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
767
768         v3s16 bp1 = getNodeBlockPos(p1);
769         v3s16 bp2 = getNodeBlockPos(p2);
770         vm->initialEmerge(bp1, bp2);
771         
772         size = p2 - p1 + 1;
773         schematic = new MapNode[size.X * size.Y * size.Z];
774         
775         u32 i = 0;
776         for (s16 z = p1.Z; z <= p2.Z; z++)
777         for (s16 y = p1.Y; y <= p2.Y; y++) {
778                 u32 vi = vm->m_area.index(p1.X, y, z);
779                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
780                         schematic[i] = vm->m_data[vi];
781                         schematic[i].param1 = 0;
782                 }
783         }
784
785         delete vm;
786         return true;
787 }
788
789
790 void DecoSchematic::applyProbabilities(std::vector<std::pair<v3s16, s16> > *plist, v3s16 p0) {
791         for (size_t i = 0; i != plist->size(); i++) {
792                 v3s16 p = (*plist)[i].first - p0;
793                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
794                 if (index < size.Z * size.Y * size.X) {
795                         s16 prob = (*plist)[i].second;
796                         if (prob != -1)
797                                 schematic[index].param1 = prob;
798                         else
799                                 schematic[index].setContent(CONTENT_IGNORE);
800                 }
801         }
802 }
803
804
805 ///////////////////////////////////////////////////////////////////////////////
806
807
808 Mapgen::Mapgen() {
809         seed        = 0;
810         water_level = 0;
811         generating  = false;
812         id          = -1;
813         vm          = NULL;
814         ndef        = NULL;
815         heightmap   = NULL;
816         biomemap    = NULL;
817 }
818
819
820 // Returns Y one under area minimum if not found
821 s16 Mapgen::findGroundLevelFull(v2s16 p2d) {
822         v3s16 em = vm->m_area.getExtent();
823         s16 y_nodes_max = vm->m_area.MaxEdge.Y;
824         s16 y_nodes_min = vm->m_area.MinEdge.Y;
825         u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y);
826         s16 y;
827         
828         for (y = y_nodes_max; y >= y_nodes_min; y--) {
829                 MapNode &n = vm->m_data[i];
830                 if (ndef->get(n).walkable)
831                         break;
832
833                 vm->m_area.add_y(em, i, -1);
834         }
835         return (y >= y_nodes_min) ? y : y_nodes_min - 1;
836 }
837
838
839 s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) {
840         v3s16 em = vm->m_area.getExtent();
841         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
842         s16 y;
843         
844         for (y = ymax; y >= ymin; y--) {
845                 MapNode &n = vm->m_data[i];
846                 if (ndef->get(n).walkable)
847                         break;
848
849                 vm->m_area.add_y(em, i, -1);
850         }
851         return y;
852 }
853
854
855 void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) {
856         if (!heightmap)
857                 return;
858         
859         //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
860         int index = 0;
861         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
862                 for (s16 x = nmin.X; x <= nmax.X; x++) {
863                         s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
864                         heightmap[index++] = y;
865                 }
866         }
867         //printf("updateHeightmap: %dus\n", t.stop());
868 }
869
870
871 void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax) {
872         bool isliquid, wasliquid, rare;
873         v3s16 em  = vm->m_area.getExtent();
874         rare = g_settings->getBool("liquid_finite");
875         int rarecnt = 0;
876
877         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
878                 for (s16 x = nmin.X; x <= nmax.X; x++) {
879                         wasliquid = true;
880
881                         u32 i = vm->m_area.index(x, nmax.Y, z);
882                         for (s16 y = nmax.Y; y >= nmin.Y; y--) {
883                                 isliquid = ndef->get(vm->m_data[i]).isLiquid();
884
885                                 // there was a change between liquid and nonliquid, add to queue. no need to add every with liquid_finite
886                                 if (isliquid != wasliquid && (!rare || !(rarecnt++ % 36)))
887                                         trans_liquid->push_back(v3s16(x, y, z));
888
889                                 wasliquid = isliquid;
890                                 vm->m_area.add_y(em, i, -1);
891                         }
892                 }
893         }
894 }
895
896
897 void Mapgen::setLighting(v3s16 nmin, v3s16 nmax, u8 light) {
898         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
899         VoxelArea a(nmin, nmax);
900
901         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
902                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
903                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
904                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
905                                 vm->m_data[i].param1 = light;
906                 }
907         }
908 }
909
910
911 void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light) {
912         if (light <= 1 || !a.contains(p))
913                 return;
914
915         u32 vi = vm->m_area.index(p);
916         MapNode &nn = vm->m_data[vi];
917
918         light--;
919         // should probably compare masked, but doesn't seem to make a difference
920         if (light <= nn.param1 || !ndef->get(nn).light_propagates)
921                 return;
922
923         nn.param1 = light;
924
925         lightSpread(a, p + v3s16(0, 0, 1), light);
926         lightSpread(a, p + v3s16(0, 1, 0), light);
927         lightSpread(a, p + v3s16(1, 0, 0), light);
928         lightSpread(a, p - v3s16(0, 0, 1), light);
929         lightSpread(a, p - v3s16(0, 1, 0), light);
930         lightSpread(a, p - v3s16(1, 0, 0), light);
931 }
932
933
934 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax) {
935         VoxelArea a(nmin, nmax);
936         bool block_is_underground = (water_level >= nmax.Y);
937
938         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
939         //TimeTaker t("updateLighting");
940
941         // first, send vertical rays of sunshine downward
942         v3s16 em = vm->m_area.getExtent();
943         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
944                 for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
945                         // see if we can get a light value from the overtop
946                         u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
947                         if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
948                                 if (block_is_underground)
949                                         continue;
950                         } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN) {
951                                 continue;
952                         }
953                         vm->m_area.add_y(em, i, -1);
954  
955                         for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
956                                 MapNode &n = vm->m_data[i];
957                                 if (!ndef->get(n).sunlight_propagates)
958                                         break;
959                                 n.param1 = LIGHT_SUN;
960                                 vm->m_area.add_y(em, i, -1);
961                         }
962                 }
963         }
964
965         // now spread the sunlight and light up any sources
966         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
967                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
968                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
969                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
970                                 MapNode &n = vm->m_data[i];
971                                 if (n.getContent() == CONTENT_IGNORE ||
972                                         !ndef->get(n).light_propagates)
973                                         continue;
974
975                                 u8 light_produced = ndef->get(n).light_source & 0x0F;
976                                 if (light_produced)
977                                         n.param1 = light_produced;
978
979                                 u8 light = n.param1 & 0x0F;
980                                 if (light) {
981                                         lightSpread(a, v3s16(x,     y,     z + 1), light - 1);
982                                         lightSpread(a, v3s16(x,     y + 1, z    ), light - 1);
983                                         lightSpread(a, v3s16(x + 1, y,     z    ), light - 1);
984                                         lightSpread(a, v3s16(x,     y,     z - 1), light - 1);
985                                         lightSpread(a, v3s16(x,     y - 1, z    ), light - 1);
986                                         lightSpread(a, v3s16(x - 1, y,     z    ), light - 1);
987                                 }
988                         }
989                 }
990         }
991
992         //printf("updateLighting: %dms\n", t.stop());
993 }
994
995
996 void Mapgen::calcLightingOld(v3s16 nmin, v3s16 nmax) {
997         enum LightBank banks[2] = {LIGHTBANK_DAY, LIGHTBANK_NIGHT};
998         VoxelArea a(nmin, nmax);
999         bool block_is_underground = (water_level > nmax.Y);
1000         bool sunlight = !block_is_underground;
1001
1002         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
1003
1004         for (int i = 0; i < 2; i++) {
1005                 enum LightBank bank = banks[i];
1006                 std::set<v3s16> light_sources;
1007                 std::map<v3s16, u8> unlight_from;
1008
1009                 voxalgo::clearLightAndCollectSources(*vm, a, bank, ndef,
1010                                                                                          light_sources, unlight_from);
1011                 voxalgo::propagateSunlight(*vm, a, sunlight, light_sources, ndef);
1012
1013                 vm->unspreadLight(bank, unlight_from, light_sources, ndef);
1014                 vm->spreadLight(bank, light_sources, ndef);
1015         }
1016 }
1017  
1018  
1019 //////////////////////// Mapgen V6 parameter read/write
1020  
1021 bool MapgenV6Params::readParams(Settings *settings) {
1022         freq_desert = settings->getFloat("mgv6_freq_desert");
1023         freq_beach  = settings->getFloat("mgv6_freq_beach");
1024
1025         bool success = 
1026                 settings->getNoiseParams("mgv6_np_terrain_base",   np_terrain_base)   &&
1027                 settings->getNoiseParams("mgv6_np_terrain_higher", np_terrain_higher) &&
1028                 settings->getNoiseParams("mgv6_np_steepness",      np_steepness)      &&
1029                 settings->getNoiseParams("mgv6_np_height_select",  np_height_select)  &&
1030                 settings->getNoiseParams("mgv6_np_mud",            np_mud)            &&
1031                 settings->getNoiseParams("mgv6_np_beach",          np_beach)          &&
1032                 settings->getNoiseParams("mgv6_np_biome",          np_biome)          &&
1033                 settings->getNoiseParams("mgv6_np_cave",           np_cave)           &&
1034                 settings->getNoiseParams("mgv6_np_humidity",       np_humidity)       &&
1035                 settings->getNoiseParams("mgv6_np_trees",          np_trees)          &&
1036                 settings->getNoiseParams("mgv6_np_apple_trees",    np_apple_trees);
1037         return success;
1038 }
1039  
1040  
1041 void MapgenV6Params::writeParams(Settings *settings) {
1042         settings->setFloat("mgv6_freq_desert", freq_desert);
1043         settings->setFloat("mgv6_freq_beach",  freq_beach);
1044  
1045         settings->setNoiseParams("mgv6_np_terrain_base",   np_terrain_base);
1046         settings->setNoiseParams("mgv6_np_terrain_higher", np_terrain_higher);
1047         settings->setNoiseParams("mgv6_np_steepness",      np_steepness);
1048         settings->setNoiseParams("mgv6_np_height_select",  np_height_select);
1049         settings->setNoiseParams("mgv6_np_mud",            np_mud);
1050         settings->setNoiseParams("mgv6_np_beach",          np_beach);
1051         settings->setNoiseParams("mgv6_np_biome",          np_biome);
1052         settings->setNoiseParams("mgv6_np_cave",           np_cave);
1053         settings->setNoiseParams("mgv6_np_humidity",       np_humidity);
1054         settings->setNoiseParams("mgv6_np_trees",          np_trees);
1055         settings->setNoiseParams("mgv6_np_apple_trees",    np_apple_trees);
1056 }
1057
1058
1059 bool MapgenV7Params::readParams(Settings *settings) {
1060         bool success = 
1061                 settings->getNoiseParams("mgv7_np_terrain_base",    np_terrain_base)    &&
1062                 settings->getNoiseParams("mgv7_np_terrain_alt",     np_terrain_alt)     &&
1063                 settings->getNoiseParams("mgv7_np_terrain_mod",     np_terrain_mod)     &&
1064                 settings->getNoiseParams("mgv7_np_terrain_persist", np_terrain_persist) &&
1065                 settings->getNoiseParams("mgv7_np_height_select",   np_height_select)   &&
1066                 settings->getNoiseParams("mgv7_np_ridge",           np_ridge);
1067         return success;
1068 }
1069
1070
1071 void MapgenV7Params::writeParams(Settings *settings) {
1072         settings->setNoiseParams("mgv7_np_terrain_base",    np_terrain_base);
1073         settings->setNoiseParams("mgv7_np_terrain_alt",     np_terrain_alt);
1074         settings->setNoiseParams("mgv7_np_terrain_mod",     np_terrain_mod);
1075         settings->setNoiseParams("mgv7_np_terrain_persist", np_terrain_persist);
1076         settings->setNoiseParams("mgv7_np_height_select",   np_height_select);
1077         settings->setNoiseParams("mgv7_np_ridge",           np_ridge);
1078 }
1079
1080
1081 /////////////////////////////////// legacy static functions for farmesh
1082
1083 s16 Mapgen::find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision) {
1084         //just need to return something
1085         s16 level = 5;
1086         return level;
1087 }
1088
1089
1090 bool Mapgen::get_have_beach(u64 seed, v2s16 p2d) {
1091         double sandnoise = noise2d_perlin(
1092                                 0.2+(float)p2d.X/250, 0.7+(float)p2d.Y/250,
1093                                 seed+59420, 3, 0.50);
1094  
1095         return (sandnoise > 0.15);
1096 }
1097
1098
1099 double Mapgen::tree_amount_2d(u64 seed, v2s16 p) {
1100         double noise = noise2d_perlin(
1101                         0.5+(float)p.X/125, 0.5+(float)p.Y/125,
1102                         seed+2, 4, 0.66);
1103         double zeroval = -0.39;
1104         if(noise < zeroval)
1105                 return 0;
1106         else
1107                 return 0.04 * (noise-zeroval) / (1.0-zeroval);
1108 }