e7e002c160fc439e374929403cbf5aa927fa122b
[oweals/minetest.git] / src / script / lua_api / l_mapgen.cpp
1 /*
2 Minetest
3 Copyright (C) 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 "lua_api/l_mapgen.h"
21 #include "lua_api/l_internal.h"
22 #include "lua_api/l_vmanip.h"
23 #include "common/c_converter.h"
24 #include "common/c_content.h"
25 #include "cpp_api/s_security.h"
26 #include "util/serialize.h"
27 #include "server.h"
28 #include "environment.h"
29 #include "emerge.h"
30 #include "mapgen/mg_biome.h"
31 #include "mapgen/mg_ore.h"
32 #include "mapgen/mg_decoration.h"
33 #include "mapgen/mg_schematic.h"
34 #include "mapgen/mapgen_v5.h"
35 #include "mapgen/mapgen_v7.h"
36 #include "filesys.h"
37 #include "settings.h"
38 #include "log.h"
39
40 struct EnumString ModApiMapgen::es_BiomeTerrainType[] =
41 {
42         {BIOMETYPE_NORMAL, "normal"},
43         {0, NULL},
44 };
45
46 struct EnumString ModApiMapgen::es_DecorationType[] =
47 {
48         {DECO_SIMPLE,    "simple"},
49         {DECO_SCHEMATIC, "schematic"},
50         {DECO_LSYSTEM,   "lsystem"},
51         {0, NULL},
52 };
53
54 struct EnumString ModApiMapgen::es_MapgenObject[] =
55 {
56         {MGOBJ_VMANIP,    "voxelmanip"},
57         {MGOBJ_HEIGHTMAP, "heightmap"},
58         {MGOBJ_BIOMEMAP,  "biomemap"},
59         {MGOBJ_HEATMAP,   "heatmap"},
60         {MGOBJ_HUMIDMAP,  "humiditymap"},
61         {MGOBJ_GENNOTIFY, "gennotify"},
62         {0, NULL},
63 };
64
65 struct EnumString ModApiMapgen::es_OreType[] =
66 {
67         {ORE_SCATTER, "scatter"},
68         {ORE_SHEET,   "sheet"},
69         {ORE_PUFF,    "puff"},
70         {ORE_BLOB,    "blob"},
71         {ORE_VEIN,    "vein"},
72         {ORE_STRATUM, "stratum"},
73         {0, NULL},
74 };
75
76 struct EnumString ModApiMapgen::es_Rotation[] =
77 {
78         {ROTATE_0,    "0"},
79         {ROTATE_90,   "90"},
80         {ROTATE_180,  "180"},
81         {ROTATE_270,  "270"},
82         {ROTATE_RAND, "random"},
83         {0, NULL},
84 };
85
86 struct EnumString ModApiMapgen::es_SchematicFormatType[] =
87 {
88         {SCHEM_FMT_HANDLE, "handle"},
89         {SCHEM_FMT_MTS,    "mts"},
90         {SCHEM_FMT_LUA,    "lua"},
91         {0, NULL},
92 };
93
94 ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr);
95
96 Biome *get_or_load_biome(lua_State *L, int index,
97         BiomeManager *biomemgr);
98 Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef);
99 size_t get_biome_list(lua_State *L, int index,
100         BiomeManager *biomemgr, std::unordered_set<u8> *biome_id_list);
101
102 Schematic *get_or_load_schematic(lua_State *L, int index,
103         SchematicManager *schemmgr, StringMap *replace_names);
104 Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef,
105         StringMap *replace_names);
106 Schematic *load_schematic_from_def(lua_State *L, int index,
107         const NodeDefManager *ndef, StringMap *replace_names);
108 bool read_schematic_def(lua_State *L, int index,
109         Schematic *schem, std::vector<std::string> *names);
110
111 bool read_deco_simple(lua_State *L, DecoSimple *deco);
112 bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco);
113
114
115 ///////////////////////////////////////////////////////////////////////////////
116
117 ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr)
118 {
119         if (index < 0)
120                 index = lua_gettop(L) + 1 + index;
121
122         // If a number, assume this is a handle to an object def
123         if (lua_isnumber(L, index))
124                 return objmgr->get(lua_tointeger(L, index));
125
126         // If a string, assume a name is given instead
127         if (lua_isstring(L, index))
128                 return objmgr->getByName(lua_tostring(L, index));
129
130         return NULL;
131 }
132
133 ///////////////////////////////////////////////////////////////////////////////
134
135 Schematic *get_or_load_schematic(lua_State *L, int index,
136         SchematicManager *schemmgr, StringMap *replace_names)
137 {
138         if (index < 0)
139                 index = lua_gettop(L) + 1 + index;
140
141         Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr);
142         if (schem)
143                 return schem;
144
145         schem = load_schematic(L, index, schemmgr->getNodeDef(),
146                 replace_names);
147         if (!schem)
148                 return NULL;
149
150         if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) {
151                 delete schem;
152                 return NULL;
153         }
154
155         return schem;
156 }
157
158
159 Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef,
160         StringMap *replace_names)
161 {
162         if (index < 0)
163                 index = lua_gettop(L) + 1 + index;
164
165         Schematic *schem = NULL;
166
167         if (lua_istable(L, index)) {
168                 schem = load_schematic_from_def(L, index, ndef,
169                         replace_names);
170                 if (!schem) {
171                         delete schem;
172                         return NULL;
173                 }
174         } else if (lua_isnumber(L, index)) {
175                 return NULL;
176         } else if (lua_isstring(L, index)) {
177                 schem = SchematicManager::create(SCHEMATIC_NORMAL);
178
179                 std::string filepath = lua_tostring(L, index);
180                 if (!fs::IsPathAbsolute(filepath))
181                         filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath;
182
183                 if (!schem->loadSchematicFromFile(filepath, ndef,
184                                 replace_names)) {
185                         delete schem;
186                         return NULL;
187                 }
188         }
189
190         return schem;
191 }
192
193
194 Schematic *load_schematic_from_def(lua_State *L, int index,
195         const NodeDefManager *ndef, StringMap *replace_names)
196 {
197         Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL);
198
199         if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) {
200                 delete schem;
201                 return NULL;
202         }
203
204         size_t num_nodes = schem->m_nodenames.size();
205
206         schem->m_nnlistsizes.push_back(num_nodes);
207
208         if (replace_names) {
209                 for (size_t i = 0; i != num_nodes; i++) {
210                         StringMap::iterator it = replace_names->find(schem->m_nodenames[i]);
211                         if (it != replace_names->end())
212                                 schem->m_nodenames[i] = it->second;
213                 }
214         }
215
216         if (ndef)
217                 ndef->pendNodeResolve(schem);
218
219         return schem;
220 }
221
222
223 bool read_schematic_def(lua_State *L, int index,
224         Schematic *schem, std::vector<std::string> *names)
225 {
226         if (!lua_istable(L, index))
227                 return false;
228
229         //// Get schematic size
230         lua_getfield(L, index, "size");
231         v3s16 size = check_v3s16(L, -1);
232         lua_pop(L, 1);
233
234         schem->size = size;
235
236         //// Get schematic data
237         lua_getfield(L, index, "data");
238         luaL_checktype(L, -1, LUA_TTABLE);
239
240         u32 numnodes = size.X * size.Y * size.Z;
241         schem->schemdata = new MapNode[numnodes];
242
243         size_t names_base = names->size();
244         std::unordered_map<std::string, content_t> name_id_map;
245
246         u32 i = 0;
247         for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) {
248                 if (i >= numnodes)
249                         continue;
250
251                 //// Read name
252                 std::string name;
253                 if (!getstringfield(L, -1, "name", name))
254                         throw LuaError("Schematic data definition with missing name field");
255
256                 //// Read param1/prob
257                 u8 param1;
258                 if (!getintfield(L, -1, "param1", param1) &&
259                         !getintfield(L, -1, "prob", param1))
260                         param1 = MTSCHEM_PROB_ALWAYS_OLD;
261
262                 //// Read param2
263                 u8 param2 = getintfield_default(L, -1, "param2", 0);
264
265                 //// Find or add new nodename-to-ID mapping
266                 std::unordered_map<std::string, content_t>::iterator it = name_id_map.find(name);
267                 content_t name_index;
268                 if (it != name_id_map.end()) {
269                         name_index = it->second;
270                 } else {
271                         name_index = names->size() - names_base;
272                         name_id_map[name] = name_index;
273                         names->push_back(name);
274                 }
275
276                 //// Perform probability/force_place fixup on param1
277                 param1 >>= 1;
278                 if (getboolfield_default(L, -1, "force_place", false))
279                         param1 |= MTSCHEM_FORCE_PLACE;
280
281                 //// Actually set the node in the schematic
282                 schem->schemdata[i] = MapNode(name_index, param1, param2);
283         }
284
285         if (i != numnodes) {
286                 errorstream << "read_schematic_def: incorrect number of "
287                         "nodes provided in raw schematic data (got " << i <<
288                         ", expected " << numnodes << ")." << std::endl;
289                 return false;
290         }
291
292         //// Get Y-slice probability values (if present)
293         schem->slice_probs = new u8[size.Y];
294         for (i = 0; i != (u32) size.Y; i++)
295                 schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS;
296
297         lua_getfield(L, index, "yslice_prob");
298         if (lua_istable(L, -1)) {
299                 for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
300                         u16 ypos;
301                         if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) ||
302                                 !getintfield(L, -1, "prob", schem->slice_probs[ypos]))
303                                 continue;
304
305                         schem->slice_probs[ypos] >>= 1;
306                 }
307         }
308
309         return true;
310 }
311
312
313 void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names)
314 {
315         if (index < 0)
316                 index = lua_gettop(L) + 1 + index;
317
318         lua_pushnil(L);
319         while (lua_next(L, index)) {
320                 std::string replace_from;
321                 std::string replace_to;
322
323                 if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format
324                         lua_rawgeti(L, -1, 1);
325                         if (!lua_isstring(L, -1))
326                                 throw LuaError("schematics: replace_from field is not a string");
327                         replace_from = lua_tostring(L, -1);
328                         lua_pop(L, 1);
329
330                         lua_rawgeti(L, -1, 2);
331                         if (!lua_isstring(L, -1))
332                                 throw LuaError("schematics: replace_to field is not a string");
333                         replace_to = lua_tostring(L, -1);
334                         lua_pop(L, 1);
335                 } else { // New {x = "y", ...} format
336                         if (!lua_isstring(L, -2))
337                                 throw LuaError("schematics: replace_from field is not a string");
338                         replace_from = lua_tostring(L, -2);
339                         if (!lua_isstring(L, -1))
340                                 throw LuaError("schematics: replace_to field is not a string");
341                         replace_to = lua_tostring(L, -1);
342                 }
343
344                 replace_names->insert(std::make_pair(replace_from, replace_to));
345                 lua_pop(L, 1);
346         }
347 }
348
349 ///////////////////////////////////////////////////////////////////////////////
350
351 Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr)
352 {
353         if (index < 0)
354                 index = lua_gettop(L) + 1 + index;
355
356         Biome *biome = (Biome *)get_objdef(L, index, biomemgr);
357         if (biome)
358                 return biome;
359
360         biome = read_biome_def(L, index, biomemgr->getNodeDef());
361         if (!biome)
362                 return NULL;
363
364         if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) {
365                 delete biome;
366                 return NULL;
367         }
368
369         return biome;
370 }
371
372
373 Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef)
374 {
375         if (!lua_istable(L, index))
376                 return NULL;
377
378         BiomeType biometype = (BiomeType)getenumfield(L, index, "type",
379                 ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL);
380         Biome *b = BiomeManager::create(biometype);
381
382         b->name            = getstringfield_default(L, index, "name", "");
383         b->depth_top       = getintfield_default(L,    index, "depth_top",       0);
384         b->depth_filler    = getintfield_default(L,    index, "depth_filler",    -31000);
385         b->depth_water_top = getintfield_default(L,    index, "depth_water_top", 0);
386         b->depth_riverbed  = getintfield_default(L,    index, "depth_riverbed",  0);
387         b->heat_point      = getfloatfield_default(L,  index, "heat_point",      0.f);
388         b->humidity_point  = getfloatfield_default(L,  index, "humidity_point",  0.f);
389         b->vertical_blend  = getintfield_default(L,    index, "vertical_blend",  0);
390         b->flags           = 0; // reserved
391
392         b->min_pos = getv3s16field_default(
393                 L, index, "min_pos", v3s16(-31000, -31000, -31000));
394         getintfield(L, index, "y_min", b->min_pos.Y);
395         b->max_pos = getv3s16field_default(
396                 L, index, "max_pos", v3s16(31000, 31000, 31000));
397         getintfield(L, index, "y_max", b->max_pos.Y);
398
399         std::vector<std::string> &nn = b->m_nodenames;
400         nn.push_back(getstringfield_default(L, index, "node_top",           ""));
401         nn.push_back(getstringfield_default(L, index, "node_filler",        ""));
402         nn.push_back(getstringfield_default(L, index, "node_stone",         ""));
403         nn.push_back(getstringfield_default(L, index, "node_water_top",     ""));
404         nn.push_back(getstringfield_default(L, index, "node_water",         ""));
405         nn.push_back(getstringfield_default(L, index, "node_river_water",   ""));
406         nn.push_back(getstringfield_default(L, index, "node_riverbed",      ""));
407         nn.push_back(getstringfield_default(L, index, "node_dust",          ""));
408
409         size_t nnames = getstringlistfield(L, index, "node_cave_liquid", &nn);
410         // If no cave liquids defined, set list to "ignore" to trigger old hardcoded
411         // cave liquid behaviour.
412         if (nnames == 0) {
413                 nn.emplace_back("ignore");
414                 nnames = 1;
415         }
416         b->m_nnlistsizes.push_back(nnames);
417
418         nn.push_back(getstringfield_default(L, index, "node_dungeon",       ""));
419         nn.push_back(getstringfield_default(L, index, "node_dungeon_alt",   ""));
420         nn.push_back(getstringfield_default(L, index, "node_dungeon_stair", ""));
421         ndef->pendNodeResolve(b);
422
423         return b;
424 }
425
426
427 size_t get_biome_list(lua_State *L, int index,
428         BiomeManager *biomemgr, std::unordered_set<u8> *biome_id_list)
429 {
430         if (index < 0)
431                 index = lua_gettop(L) + 1 + index;
432
433         if (lua_isnil(L, index))
434                 return 0;
435
436         bool is_single = true;
437         if (lua_istable(L, index)) {
438                 lua_getfield(L, index, "name");
439                 is_single = !lua_isnil(L, -1);
440                 lua_pop(L, 1);
441         }
442
443         if (is_single) {
444                 Biome *biome = get_or_load_biome(L, index, biomemgr);
445                 if (!biome) {
446                         infostream << "get_biome_list: failed to get biome '"
447                                 << (lua_isstring(L, index) ? lua_tostring(L, index) : "")
448                                 << "'." << std::endl;
449                         return 1;
450                 }
451
452                 biome_id_list->insert(biome->index);
453                 return 0;
454         }
455
456         // returns number of failed resolutions
457         size_t fail_count = 0;
458         size_t count = 0;
459
460         for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) {
461                 count++;
462                 Biome *biome = get_or_load_biome(L, -1, biomemgr);
463                 if (!biome) {
464                         fail_count++;
465                         infostream << "get_biome_list: failed to get biome '"
466                                 << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "")
467                                 << "'" << std::endl;
468                         continue;
469                 }
470
471                 biome_id_list->insert(biome->index);
472         }
473
474         return fail_count;
475 }
476
477 ///////////////////////////////////////////////////////////////////////////////
478
479 // get_biome_id(biomename)
480 // returns the biome id as used in biomemap and returned by 'get_biome_data()'
481 int ModApiMapgen::l_get_biome_id(lua_State *L)
482 {
483         NO_MAP_LOCK_REQUIRED;
484
485         const char *biome_str = lua_tostring(L, 1);
486         if (!biome_str)
487                 return 0;
488
489         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
490         if (!bmgr)
491                 return 0;
492
493         Biome *biome = (Biome *)bmgr->getByName(biome_str);
494         if (!biome || biome->index == OBJDEF_INVALID_INDEX)
495                 return 0;
496
497         lua_pushinteger(L, biome->index);
498
499         return 1;
500 }
501
502
503 // get_biome_name(biome_id)
504 // returns the biome name string
505 int ModApiMapgen::l_get_biome_name(lua_State *L)
506 {
507         NO_MAP_LOCK_REQUIRED;
508
509         int biome_id = luaL_checkinteger(L, 1);
510
511         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
512         if (!bmgr)
513                 return 0;
514
515         Biome *b = (Biome *)bmgr->getRaw(biome_id);
516         lua_pushstring(L, b->name.c_str());
517
518         return 1;
519 }
520
521
522 // get_heat(pos)
523 // returns the heat at the position
524 int ModApiMapgen::l_get_heat(lua_State *L)
525 {
526         NO_MAP_LOCK_REQUIRED;
527
528         v3s16 pos = read_v3s16(L, 1);
529
530         NoiseParams np_heat;
531         NoiseParams np_heat_blend;
532
533         MapSettingsManager *settingsmgr =
534                 getServer(L)->getEmergeManager()->map_settings_mgr;
535
536         if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat",
537                         &np_heat) ||
538                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend",
539                         &np_heat_blend))
540                 return 0;
541
542         std::string value;
543         if (!settingsmgr->getMapSetting("seed", &value))
544                 return 0;
545         std::istringstream ss(value);
546         u64 seed;
547         ss >> seed;
548
549         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
550         if (!bmgr)
551                 return 0;
552
553         float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed);
554         if (!heat)
555                 return 0;
556
557         lua_pushnumber(L, heat);
558
559         return 1;
560 }
561
562
563 // get_humidity(pos)
564 // returns the humidity at the position
565 int ModApiMapgen::l_get_humidity(lua_State *L)
566 {
567         NO_MAP_LOCK_REQUIRED;
568
569         v3s16 pos = read_v3s16(L, 1);
570
571         NoiseParams np_humidity;
572         NoiseParams np_humidity_blend;
573
574         MapSettingsManager *settingsmgr =
575                 getServer(L)->getEmergeManager()->map_settings_mgr;
576
577         if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity",
578                         &np_humidity) ||
579                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend",
580                         &np_humidity_blend))
581                 return 0;
582
583         std::string value;
584         if (!settingsmgr->getMapSetting("seed", &value))
585                 return 0;
586         std::istringstream ss(value);
587         u64 seed;
588         ss >> seed;
589
590         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
591         if (!bmgr)
592                 return 0;
593
594         float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity,
595                 np_humidity_blend, seed);
596         if (!humidity)
597                 return 0;
598
599         lua_pushnumber(L, humidity);
600
601         return 1;
602 }
603
604
605 // get_biome_data(pos)
606 // returns a table containing the biome id, heat and humidity at the position
607 int ModApiMapgen::l_get_biome_data(lua_State *L)
608 {
609         NO_MAP_LOCK_REQUIRED;
610
611         v3s16 pos = read_v3s16(L, 1);
612
613         NoiseParams np_heat;
614         NoiseParams np_heat_blend;
615         NoiseParams np_humidity;
616         NoiseParams np_humidity_blend;
617
618         MapSettingsManager *settingsmgr =
619                 getServer(L)->getEmergeManager()->map_settings_mgr;
620
621         if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat",
622                         &np_heat) ||
623                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend",
624                         &np_heat_blend) ||
625                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity",
626                         &np_humidity) ||
627                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend",
628                         &np_humidity_blend))
629                 return 0;
630
631         std::string value;
632         if (!settingsmgr->getMapSetting("seed", &value))
633                 return 0;
634         std::istringstream ss(value);
635         u64 seed;
636         ss >> seed;
637
638         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
639         if (!bmgr)
640                 return 0;
641
642         float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed);
643         if (!heat)
644                 return 0;
645
646         float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity,
647                 np_humidity_blend, seed);
648         if (!humidity)
649                 return 0;
650
651         Biome *biome = (Biome *)bmgr->getBiomeFromNoiseOriginal(heat, humidity, pos);
652         if (!biome || biome->index == OBJDEF_INVALID_INDEX)
653                 return 0;
654
655         lua_newtable(L);
656
657         lua_pushinteger(L, biome->index);
658         lua_setfield(L, -2, "biome");
659
660         lua_pushnumber(L, heat);
661         lua_setfield(L, -2, "heat");
662
663         lua_pushnumber(L, humidity);
664         lua_setfield(L, -2, "humidity");
665
666         return 1;
667 }
668
669
670 // get_mapgen_object(objectname)
671 // returns the requested object used during map generation
672 int ModApiMapgen::l_get_mapgen_object(lua_State *L)
673 {
674         NO_MAP_LOCK_REQUIRED;
675
676         const char *mgobjstr = lua_tostring(L, 1);
677
678         int mgobjint;
679         if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
680                 return 0;
681
682         enum MapgenObject mgobj = (MapgenObject)mgobjint;
683
684         EmergeManager *emerge = getServer(L)->getEmergeManager();
685         Mapgen *mg = emerge->getCurrentMapgen();
686         if (!mg)
687                 throw LuaError("Must only be called in a mapgen thread!");
688
689         size_t maplen = mg->csize.X * mg->csize.Z;
690
691         switch (mgobj) {
692         case MGOBJ_VMANIP: {
693                 MMVManip *vm = mg->vm;
694
695                 // VoxelManip object
696                 LuaVoxelManip *o = new LuaVoxelManip(vm, true);
697                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
698                 luaL_getmetatable(L, "VoxelManip");
699                 lua_setmetatable(L, -2);
700
701                 // emerged min pos
702                 push_v3s16(L, vm->m_area.MinEdge);
703
704                 // emerged max pos
705                 push_v3s16(L, vm->m_area.MaxEdge);
706
707                 return 3;
708         }
709         case MGOBJ_HEIGHTMAP: {
710                 if (!mg->heightmap)
711                         return 0;
712
713                 lua_newtable(L);
714                 for (size_t i = 0; i != maplen; i++) {
715                         lua_pushinteger(L, mg->heightmap[i]);
716                         lua_rawseti(L, -2, i + 1);
717                 }
718
719                 return 1;
720         }
721         case MGOBJ_BIOMEMAP: {
722                 if (!mg->biomegen)
723                         return 0;
724
725                 lua_newtable(L);
726                 for (size_t i = 0; i != maplen; i++) {
727                         lua_pushinteger(L, mg->biomegen->biomemap[i]);
728                         lua_rawseti(L, -2, i + 1);
729                 }
730
731                 return 1;
732         }
733         case MGOBJ_HEATMAP: {
734                 if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
735                         return 0;
736
737                 BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;
738
739                 lua_newtable(L);
740                 for (size_t i = 0; i != maplen; i++) {
741                         lua_pushnumber(L, bg->heatmap[i]);
742                         lua_rawseti(L, -2, i + 1);
743                 }
744
745                 return 1;
746         }
747
748         case MGOBJ_HUMIDMAP: {
749                 if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
750                         return 0;
751
752                 BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;
753
754                 lua_newtable(L);
755                 for (size_t i = 0; i != maplen; i++) {
756                         lua_pushnumber(L, bg->humidmap[i]);
757                         lua_rawseti(L, -2, i + 1);
758                 }
759
760                 return 1;
761         }
762         case MGOBJ_GENNOTIFY: {
763                 std::map<std::string, std::vector<v3s16> >event_map;
764                 std::map<std::string, std::vector<v3s16> >::iterator it;
765
766                 mg->gennotify.getEvents(event_map);
767
768                 lua_newtable(L);
769                 for (it = event_map.begin(); it != event_map.end(); ++it) {
770                         lua_newtable(L);
771
772                         for (size_t j = 0; j != it->second.size(); j++) {
773                                 push_v3s16(L, it->second[j]);
774                                 lua_rawseti(L, -2, j + 1);
775                         }
776
777                         lua_setfield(L, -2, it->first.c_str());
778                 }
779
780                 return 1;
781         }
782         }
783
784         return 0;
785 }
786
787
788 // get_spawn_level(x = num, z = num)
789 int ModApiMapgen::l_get_spawn_level(lua_State *L)
790 {
791         NO_MAP_LOCK_REQUIRED;
792
793         s16 x = luaL_checkinteger(L, 1);
794         s16 z = luaL_checkinteger(L, 2);
795
796         EmergeManager *emerge = getServer(L)->getEmergeManager();
797         int spawn_level = emerge->getSpawnLevelAtPoint(v2s16(x, z));
798         // Unsuitable spawn point
799         if (spawn_level == MAX_MAP_GENERATION_LIMIT)
800                 return 0;
801
802         // 'findSpawnPos()' in server.cpp adds at least 1
803         lua_pushinteger(L, spawn_level + 1);
804
805         return 1;
806 }
807
808
809 int ModApiMapgen::l_get_mapgen_params(lua_State *L)
810 {
811         NO_MAP_LOCK_REQUIRED;
812
813         log_deprecated(L, "get_mapgen_params is deprecated; "
814                 "use get_mapgen_setting instead");
815
816         std::string value;
817
818         MapSettingsManager *settingsmgr =
819                 getServer(L)->getEmergeManager()->map_settings_mgr;
820
821         lua_newtable(L);
822
823         settingsmgr->getMapSetting("mg_name", &value);
824         lua_pushstring(L, value.c_str());
825         lua_setfield(L, -2, "mgname");
826
827         settingsmgr->getMapSetting("seed", &value);
828         std::istringstream ss(value);
829         u64 seed;
830         ss >> seed;
831         lua_pushinteger(L, seed);
832         lua_setfield(L, -2, "seed");
833
834         settingsmgr->getMapSetting("water_level", &value);
835         lua_pushinteger(L, stoi(value, -32768, 32767));
836         lua_setfield(L, -2, "water_level");
837
838         settingsmgr->getMapSetting("chunksize", &value);
839         lua_pushinteger(L, stoi(value, -32768, 32767));
840         lua_setfield(L, -2, "chunksize");
841
842         settingsmgr->getMapSetting("mg_flags", &value);
843         lua_pushstring(L, value.c_str());
844         lua_setfield(L, -2, "flags");
845
846         return 1;
847 }
848
849
850 // set_mapgen_params(params)
851 // set mapgen parameters
852 int ModApiMapgen::l_set_mapgen_params(lua_State *L)
853 {
854         NO_MAP_LOCK_REQUIRED;
855
856         log_deprecated(L, "set_mapgen_params is deprecated; "
857                 "use set_mapgen_setting instead");
858
859         if (!lua_istable(L, 1))
860                 return 0;
861
862         MapSettingsManager *settingsmgr =
863                 getServer(L)->getEmergeManager()->map_settings_mgr;
864
865         lua_getfield(L, 1, "mgname");
866         if (lua_isstring(L, -1))
867                 settingsmgr->setMapSetting("mg_name", readParam<std::string>(L, -1), true);
868
869         lua_getfield(L, 1, "seed");
870         if (lua_isnumber(L, -1))
871                 settingsmgr->setMapSetting("seed", readParam<std::string>(L, -1), true);
872
873         lua_getfield(L, 1, "water_level");
874         if (lua_isnumber(L, -1))
875                 settingsmgr->setMapSetting("water_level", readParam<std::string>(L, -1), true);
876
877         lua_getfield(L, 1, "chunksize");
878         if (lua_isnumber(L, -1))
879                 settingsmgr->setMapSetting("chunksize", readParam<std::string>(L, -1), true);
880
881         warn_if_field_exists(L, 1, "flagmask",
882                 "Deprecated: flags field now includes unset flags.");
883
884         lua_getfield(L, 1, "flags");
885         if (lua_isstring(L, -1))
886                 settingsmgr->setMapSetting("mg_flags", readParam<std::string>(L, -1), true);
887
888         return 0;
889 }
890
891 // get_mapgen_setting(name)
892 int ModApiMapgen::l_get_mapgen_setting(lua_State *L)
893 {
894         NO_MAP_LOCK_REQUIRED;
895
896         std::string value;
897         MapSettingsManager *settingsmgr =
898                 getServer(L)->getEmergeManager()->map_settings_mgr;
899
900         const char *name = luaL_checkstring(L, 1);
901         if (!settingsmgr->getMapSetting(name, &value))
902                 return 0;
903
904         lua_pushstring(L, value.c_str());
905         return 1;
906 }
907
908 // get_mapgen_setting_noiseparams(name)
909 int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L)
910 {
911         NO_MAP_LOCK_REQUIRED;
912
913         NoiseParams np;
914         MapSettingsManager *settingsmgr =
915                 getServer(L)->getEmergeManager()->map_settings_mgr;
916
917         const char *name = luaL_checkstring(L, 1);
918         if (!settingsmgr->getMapSettingNoiseParams(name, &np))
919                 return 0;
920
921         push_noiseparams(L, &np);
922         return 1;
923 }
924
925 // set_mapgen_setting(name, value, override_meta)
926 // set mapgen config values
927 int ModApiMapgen::l_set_mapgen_setting(lua_State *L)
928 {
929         NO_MAP_LOCK_REQUIRED;
930
931         MapSettingsManager *settingsmgr =
932                 getServer(L)->getEmergeManager()->map_settings_mgr;
933
934         const char *name   = luaL_checkstring(L, 1);
935         const char *value  = luaL_checkstring(L, 2);
936         bool override_meta = readParam<bool>(L, 3, false);
937
938         if (!settingsmgr->setMapSetting(name, value, override_meta)) {
939                 errorstream << "set_mapgen_setting: cannot set '"
940                         << name << "' after initialization" << std::endl;
941         }
942
943         return 0;
944 }
945
946
947 // set_mapgen_setting_noiseparams(name, noiseparams, set_default)
948 // set mapgen config values for noise parameters
949 int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L)
950 {
951         NO_MAP_LOCK_REQUIRED;
952
953         MapSettingsManager *settingsmgr =
954                 getServer(L)->getEmergeManager()->map_settings_mgr;
955
956         const char *name = luaL_checkstring(L, 1);
957
958         NoiseParams np;
959         if (!read_noiseparams(L, 2, &np)) {
960                 errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name
961                         << "'; invalid noiseparams table" << std::endl;
962                 return 0;
963         }
964
965         bool override_meta = readParam<bool>(L, 3, false);
966
967         if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) {
968                 errorstream << "set_mapgen_setting_noiseparams: cannot set '"
969                         << name << "' after initialization" << std::endl;
970         }
971
972         return 0;
973 }
974
975
976 // set_noiseparams(name, noiseparams, set_default)
977 // set global config values for noise parameters
978 int ModApiMapgen::l_set_noiseparams(lua_State *L)
979 {
980         NO_MAP_LOCK_REQUIRED;
981
982         const char *name = luaL_checkstring(L, 1);
983
984         NoiseParams np;
985         if (!read_noiseparams(L, 2, &np)) {
986                 errorstream << "set_noiseparams: cannot set '" << name
987                         << "'; invalid noiseparams table" << std::endl;
988                 return 0;
989         }
990
991         bool set_default = !lua_isboolean(L, 3) || readParam<bool>(L, 3);
992
993         g_settings->setNoiseParams(name, np, set_default);
994
995         return 0;
996 }
997
998
999 // get_noiseparams(name)
1000 int ModApiMapgen::l_get_noiseparams(lua_State *L)
1001 {
1002         NO_MAP_LOCK_REQUIRED;
1003
1004         std::string name = luaL_checkstring(L, 1);
1005
1006         NoiseParams np;
1007         if (!g_settings->getNoiseParams(name, np))
1008                 return 0;
1009
1010         push_noiseparams(L, &np);
1011         return 1;
1012 }
1013
1014
1015 // set_gen_notify(flags, {deco_id_table})
1016 int ModApiMapgen::l_set_gen_notify(lua_State *L)
1017 {
1018         NO_MAP_LOCK_REQUIRED;
1019
1020         u32 flags = 0, flagmask = 0;
1021         EmergeManager *emerge = getServer(L)->getEmergeManager();
1022
1023         if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) {
1024                 emerge->gen_notify_on &= ~flagmask;
1025                 emerge->gen_notify_on |= flags;
1026         }
1027
1028         if (lua_istable(L, 2)) {
1029                 lua_pushnil(L);
1030                 while (lua_next(L, 2)) {
1031                         if (lua_isnumber(L, -1))
1032                                 emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1));
1033                         lua_pop(L, 1);
1034                 }
1035         }
1036
1037         return 0;
1038 }
1039
1040
1041 // get_gen_notify()
1042 int ModApiMapgen::l_get_gen_notify(lua_State *L)
1043 {
1044         NO_MAP_LOCK_REQUIRED;
1045
1046         EmergeManager *emerge = getServer(L)->getEmergeManager();
1047         push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on,
1048                 emerge->gen_notify_on);
1049
1050         lua_newtable(L);
1051         int i = 1;
1052         for (u32 gen_notify_on_deco_id : emerge->gen_notify_on_deco_ids) {
1053                 lua_pushnumber(L, gen_notify_on_deco_id);
1054                 lua_rawseti(L, -2, i++);
1055         }
1056         return 2;
1057 }
1058
1059
1060 // get_decoration_id(decoration_name)
1061 // returns the decoration ID as used in gennotify
1062 int ModApiMapgen::l_get_decoration_id(lua_State *L)
1063 {
1064         NO_MAP_LOCK_REQUIRED;
1065
1066         const char *deco_str = luaL_checkstring(L, 1);
1067         if (!deco_str)
1068                 return 0;
1069
1070         DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr;
1071
1072         if (!dmgr)
1073                 return 0;
1074
1075         Decoration *deco = (Decoration *)dmgr->getByName(deco_str);
1076
1077         if (!deco)
1078                 return 0;
1079
1080         lua_pushinteger(L, deco->index);
1081
1082         return 1;
1083 }
1084
1085
1086 // register_biome({lots of stuff})
1087 int ModApiMapgen::l_register_biome(lua_State *L)
1088 {
1089         NO_MAP_LOCK_REQUIRED;
1090
1091         int index = 1;
1092         luaL_checktype(L, index, LUA_TTABLE);
1093
1094         const NodeDefManager *ndef = getServer(L)->getNodeDefManager();
1095         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
1096
1097         Biome *biome = read_biome_def(L, index, ndef);
1098         if (!biome)
1099                 return 0;
1100
1101         ObjDefHandle handle = bmgr->add(biome);
1102         if (handle == OBJDEF_INVALID_HANDLE) {
1103                 delete biome;
1104                 return 0;
1105         }
1106
1107         lua_pushinteger(L, handle);
1108         return 1;
1109 }
1110
1111
1112 // register_decoration({lots of stuff})
1113 int ModApiMapgen::l_register_decoration(lua_State *L)
1114 {
1115         NO_MAP_LOCK_REQUIRED;
1116
1117         int index = 1;
1118         luaL_checktype(L, index, LUA_TTABLE);
1119
1120         const NodeDefManager *ndef      = getServer(L)->getNodeDefManager();
1121         DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr;
1122         BiomeManager *biomemgr     = getServer(L)->getEmergeManager()->biomemgr;
1123         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1124
1125         enum DecorationType decotype = (DecorationType)getenumfield(L, index,
1126                                 "deco_type", es_DecorationType, -1);
1127
1128         Decoration *deco = decomgr->create(decotype);
1129         if (!deco) {
1130                 errorstream << "register_decoration: decoration placement type "
1131                         << decotype << " not implemented" << std::endl;
1132                 return 0;
1133         }
1134
1135         deco->name           = getstringfield_default(L, index, "name", "");
1136         deco->fill_ratio     = getfloatfield_default(L, index, "fill_ratio", 0.02);
1137         deco->y_min          = getintfield_default(L, index, "y_min", -31000);
1138         deco->y_max          = getintfield_default(L, index, "y_max", 31000);
1139         deco->nspawnby       = getintfield_default(L, index, "num_spawn_by", -1);
1140         deco->place_offset_y = getintfield_default(L, index, "place_offset_y", 0);
1141         deco->sidelen        = getintfield_default(L, index, "sidelen", 8);
1142         if (deco->sidelen <= 0) {
1143                 errorstream << "register_decoration: sidelen must be "
1144                         "greater than 0" << std::endl;
1145                 delete deco;
1146                 return 0;
1147         }
1148
1149         //// Get node name(s) to place decoration on
1150         size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames);
1151         deco->m_nnlistsizes.push_back(nread);
1152
1153         //// Get decoration flags
1154         getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL);
1155
1156         //// Get NoiseParams to define how decoration is placed
1157         lua_getfield(L, index, "noise_params");
1158         if (read_noiseparams(L, -1, &deco->np))
1159                 deco->flags |= DECO_USE_NOISE;
1160         lua_pop(L, 1);
1161
1162         //// Get biomes associated with this decoration (if any)
1163         lua_getfield(L, index, "biomes");
1164         if (get_biome_list(L, -1, biomemgr, &deco->biomes))
1165                 infostream << "register_decoration: couldn't get all biomes " << std::endl;
1166         lua_pop(L, 1);
1167
1168         //// Get node name(s) to 'spawn by'
1169         size_t nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames);
1170         deco->m_nnlistsizes.push_back(nnames);
1171         if (nnames == 0 && deco->nspawnby != -1) {
1172                 errorstream << "register_decoration: no spawn_by nodes defined,"
1173                         " but num_spawn_by specified" << std::endl;
1174         }
1175
1176         //// Handle decoration type-specific parameters
1177         bool success = false;
1178         switch (decotype) {
1179         case DECO_SIMPLE:
1180                 success = read_deco_simple(L, (DecoSimple *)deco);
1181                 break;
1182         case DECO_SCHEMATIC:
1183                 success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco);
1184                 break;
1185         case DECO_LSYSTEM:
1186                 break;
1187         }
1188
1189         if (!success) {
1190                 delete deco;
1191                 return 0;
1192         }
1193
1194         ndef->pendNodeResolve(deco);
1195
1196         ObjDefHandle handle = decomgr->add(deco);
1197         if (handle == OBJDEF_INVALID_HANDLE) {
1198                 delete deco;
1199                 return 0;
1200         }
1201
1202         lua_pushinteger(L, handle);
1203         return 1;
1204 }
1205
1206
1207 bool read_deco_simple(lua_State *L, DecoSimple *deco)
1208 {
1209         int index = 1;
1210         int param2;
1211         int param2_max;
1212
1213         deco->deco_height     = getintfield_default(L, index, "height", 1);
1214         deco->deco_height_max = getintfield_default(L, index, "height_max", 0);
1215
1216         if (deco->deco_height <= 0) {
1217                 errorstream << "register_decoration: simple decoration height"
1218                         " must be greater than 0" << std::endl;
1219                 return false;
1220         }
1221
1222         size_t nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames);
1223         deco->m_nnlistsizes.push_back(nnames);
1224
1225         if (nnames == 0) {
1226                 errorstream << "register_decoration: no decoration nodes "
1227                         "defined" << std::endl;
1228                 return false;
1229         }
1230
1231         param2 = getintfield_default(L, index, "param2", 0);
1232         param2_max = getintfield_default(L, index, "param2_max", 0);
1233
1234         if (param2 < 0 || param2 > 255 || param2_max < 0 || param2_max > 255) {
1235                 errorstream << "register_decoration: param2 or param2_max out of bounds (0-255)"
1236                         << std::endl;
1237                 return false;
1238         }
1239
1240         deco->deco_param2 = (u8)param2;
1241         deco->deco_param2_max = (u8)param2_max;
1242
1243         return true;
1244 }
1245
1246
1247 bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco)
1248 {
1249         int index = 1;
1250
1251         deco->rotation = (Rotation)getenumfield(L, index, "rotation",
1252                 ModApiMapgen::es_Rotation, ROTATE_0);
1253
1254         StringMap replace_names;
1255         lua_getfield(L, index, "replacements");
1256         if (lua_istable(L, -1))
1257                 read_schematic_replacements(L, -1, &replace_names);
1258         lua_pop(L, 1);
1259
1260         lua_getfield(L, index, "schematic");
1261         Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names);
1262         lua_pop(L, 1);
1263
1264         deco->schematic = schem;
1265         return schem != NULL;
1266 }
1267
1268
1269 // register_ore({lots of stuff})
1270 int ModApiMapgen::l_register_ore(lua_State *L)
1271 {
1272         NO_MAP_LOCK_REQUIRED;
1273
1274         int index = 1;
1275         luaL_checktype(L, index, LUA_TTABLE);
1276
1277         const NodeDefManager *ndef = getServer(L)->getNodeDefManager();
1278         BiomeManager *bmgr    = getServer(L)->getEmergeManager()->biomemgr;
1279         OreManager *oremgr    = getServer(L)->getEmergeManager()->oremgr;
1280
1281         enum OreType oretype = (OreType)getenumfield(L, index,
1282                                 "ore_type", es_OreType, ORE_SCATTER);
1283         Ore *ore = oremgr->create(oretype);
1284         if (!ore) {
1285                 errorstream << "register_ore: ore_type " << oretype << " not implemented\n";
1286                 return 0;
1287         }
1288
1289         ore->name           = getstringfield_default(L, index, "name", "");
1290         ore->ore_param2     = (u8)getintfield_default(L, index, "ore_param2", 0);
1291         ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1);
1292         ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1);
1293         ore->clust_size     = getintfield_default(L, index, "clust_size", 0);
1294         ore->noise          = NULL;
1295         ore->flags          = 0;
1296
1297         //// Get noise_threshold
1298         warn_if_field_exists(L, index, "noise_threshhold",
1299                 "Deprecated: new name is \"noise_threshold\".");
1300
1301         float nthresh;
1302         if (!getfloatfield(L, index, "noise_threshold", nthresh) &&
1303                         !getfloatfield(L, index, "noise_threshhold", nthresh))
1304                 nthresh = 0;
1305         ore->nthresh = nthresh;
1306
1307         //// Get y_min/y_max
1308         warn_if_field_exists(L, index, "height_min",
1309                 "Deprecated: new name is \"y_min\".");
1310         warn_if_field_exists(L, index, "height_max",
1311                 "Deprecated: new name is \"y_max\".");
1312
1313         int ymin, ymax;
1314         if (!getintfield(L, index, "y_min", ymin) &&
1315                 !getintfield(L, index, "height_min", ymin))
1316                 ymin = -31000;
1317         if (!getintfield(L, index, "y_max", ymax) &&
1318                 !getintfield(L, index, "height_max", ymax))
1319                 ymax = 31000;
1320         ore->y_min = ymin;
1321         ore->y_max = ymax;
1322
1323         if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) {
1324                 errorstream << "register_ore: clust_scarcity and clust_num_ores"
1325                         "must be greater than 0" << std::endl;
1326                 delete ore;
1327                 return 0;
1328         }
1329
1330         //// Get flags
1331         getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL);
1332
1333         //// Get biomes associated with this decoration (if any)
1334         lua_getfield(L, index, "biomes");
1335         if (get_biome_list(L, -1, bmgr, &ore->biomes))
1336                 infostream << "register_ore: couldn't get all biomes " << std::endl;
1337         lua_pop(L, 1);
1338
1339         //// Get noise parameters if needed
1340         lua_getfield(L, index, "noise_params");
1341         if (read_noiseparams(L, -1, &ore->np)) {
1342                 ore->flags |= OREFLAG_USE_NOISE;
1343         } else if (ore->NEEDS_NOISE) {
1344                 errorstream << "register_ore: specified ore type requires valid "
1345                         "'noise_params' parameter" << std::endl;
1346                 delete ore;
1347                 return 0;
1348         }
1349         lua_pop(L, 1);
1350
1351         //// Get type-specific parameters
1352         switch (oretype) {
1353                 case ORE_SHEET: {
1354                         OreSheet *oresheet = (OreSheet *)ore;
1355
1356                         oresheet->column_height_min = getintfield_default(L, index,
1357                                 "column_height_min", 1);
1358                         oresheet->column_height_max = getintfield_default(L, index,
1359                                 "column_height_max", ore->clust_size);
1360                         oresheet->column_midpoint_factor = getfloatfield_default(L, index,
1361                                 "column_midpoint_factor", 0.5f);
1362
1363                         break;
1364                 }
1365                 case ORE_PUFF: {
1366                         OrePuff *orepuff = (OrePuff *)ore;
1367
1368                         lua_getfield(L, index, "np_puff_top");
1369                         read_noiseparams(L, -1, &orepuff->np_puff_top);
1370                         lua_pop(L, 1);
1371
1372                         lua_getfield(L, index, "np_puff_bottom");
1373                         read_noiseparams(L, -1, &orepuff->np_puff_bottom);
1374                         lua_pop(L, 1);
1375
1376                         break;
1377                 }
1378                 case ORE_VEIN: {
1379                         OreVein *orevein = (OreVein *)ore;
1380
1381                         orevein->random_factor = getfloatfield_default(L, index,
1382                                 "random_factor", 1.f);
1383
1384                         break;
1385                 }
1386                 case ORE_STRATUM: {
1387                         OreStratum *orestratum = (OreStratum *)ore;
1388
1389                         lua_getfield(L, index, "np_stratum_thickness");
1390                         if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness))
1391                                 ore->flags |= OREFLAG_USE_NOISE2;
1392                         lua_pop(L, 1);
1393
1394                         orestratum->stratum_thickness = getintfield_default(L, index,
1395                                 "stratum_thickness", 8);
1396
1397                         break;
1398                 }
1399                 default:
1400                         break;
1401         }
1402
1403         ObjDefHandle handle = oremgr->add(ore);
1404         if (handle == OBJDEF_INVALID_HANDLE) {
1405                 delete ore;
1406                 return 0;
1407         }
1408
1409         ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", ""));
1410
1411         size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames);
1412         ore->m_nnlistsizes.push_back(nnames);
1413
1414         ndef->pendNodeResolve(ore);
1415
1416         lua_pushinteger(L, handle);
1417         return 1;
1418 }
1419
1420
1421 // register_schematic({schematic}, replacements={})
1422 int ModApiMapgen::l_register_schematic(lua_State *L)
1423 {
1424         NO_MAP_LOCK_REQUIRED;
1425
1426         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1427
1428         StringMap replace_names;
1429         if (lua_istable(L, 2))
1430                 read_schematic_replacements(L, 2, &replace_names);
1431
1432         Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(),
1433                 &replace_names);
1434         if (!schem)
1435                 return 0;
1436
1437         ObjDefHandle handle = schemmgr->add(schem);
1438         if (handle == OBJDEF_INVALID_HANDLE) {
1439                 delete schem;
1440                 return 0;
1441         }
1442
1443         lua_pushinteger(L, handle);
1444         return 1;
1445 }
1446
1447
1448 // clear_registered_biomes()
1449 int ModApiMapgen::l_clear_registered_biomes(lua_State *L)
1450 {
1451         NO_MAP_LOCK_REQUIRED;
1452
1453         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
1454         bmgr->clear();
1455         return 0;
1456 }
1457
1458
1459 // clear_registered_decorations()
1460 int ModApiMapgen::l_clear_registered_decorations(lua_State *L)
1461 {
1462         NO_MAP_LOCK_REQUIRED;
1463
1464         DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr;
1465         dmgr->clear();
1466         return 0;
1467 }
1468
1469
1470 // clear_registered_ores()
1471 int ModApiMapgen::l_clear_registered_ores(lua_State *L)
1472 {
1473         NO_MAP_LOCK_REQUIRED;
1474
1475         OreManager *omgr = getServer(L)->getEmergeManager()->oremgr;
1476         omgr->clear();
1477         return 0;
1478 }
1479
1480
1481 // clear_registered_schematics()
1482 int ModApiMapgen::l_clear_registered_schematics(lua_State *L)
1483 {
1484         NO_MAP_LOCK_REQUIRED;
1485
1486         SchematicManager *smgr = getServer(L)->getEmergeManager()->schemmgr;
1487         smgr->clear();
1488         return 0;
1489 }
1490
1491
1492 // generate_ores(vm, p1, p2, [ore_id])
1493 int ModApiMapgen::l_generate_ores(lua_State *L)
1494 {
1495         NO_MAP_LOCK_REQUIRED;
1496
1497         EmergeManager *emerge = getServer(L)->getEmergeManager();
1498
1499         Mapgen mg;
1500         mg.seed = emerge->mgparams->seed;
1501         mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
1502         mg.ndef = getServer(L)->getNodeDefManager();
1503
1504         v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
1505                         mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
1506         v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
1507                         mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
1508         sortBoxVerticies(pmin, pmax);
1509
1510         u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);
1511
1512         emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax);
1513
1514         return 0;
1515 }
1516
1517
1518 // generate_decorations(vm, p1, p2, [deco_id])
1519 int ModApiMapgen::l_generate_decorations(lua_State *L)
1520 {
1521         NO_MAP_LOCK_REQUIRED;
1522
1523         EmergeManager *emerge = getServer(L)->getEmergeManager();
1524
1525         Mapgen mg;
1526         mg.seed = emerge->mgparams->seed;
1527         mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
1528         mg.ndef = getServer(L)->getNodeDefManager();
1529
1530         v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
1531                         mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
1532         v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
1533                         mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
1534         sortBoxVerticies(pmin, pmax);
1535
1536         u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);
1537
1538         emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax);
1539
1540         return 0;
1541 }
1542
1543
1544 // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list)
1545 int ModApiMapgen::l_create_schematic(lua_State *L)
1546 {
1547         MAP_LOCK_REQUIRED;
1548
1549         const NodeDefManager *ndef = getServer(L)->getNodeDefManager();
1550
1551         const char *filename = luaL_checkstring(L, 4);
1552         CHECK_SECURE_PATH(L, filename, true);
1553
1554         Map *map = &(getEnv(L)->getMap());
1555         Schematic schem;
1556
1557         v3s16 p1 = check_v3s16(L, 1);
1558         v3s16 p2 = check_v3s16(L, 2);
1559         sortBoxVerticies(p1, p2);
1560
1561         std::vector<std::pair<v3s16, u8> > prob_list;
1562         if (lua_istable(L, 3)) {
1563                 lua_pushnil(L);
1564                 while (lua_next(L, 3)) {
1565                         if (lua_istable(L, -1)) {
1566                                 lua_getfield(L, -1, "pos");
1567                                 v3s16 pos = check_v3s16(L, -1);
1568                                 lua_pop(L, 1);
1569
1570                                 u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
1571                                 prob_list.emplace_back(pos, prob);
1572                         }
1573
1574                         lua_pop(L, 1);
1575                 }
1576         }
1577
1578         std::vector<std::pair<s16, u8> > slice_prob_list;
1579         if (lua_istable(L, 5)) {
1580                 lua_pushnil(L);
1581                 while (lua_next(L, 5)) {
1582                         if (lua_istable(L, -1)) {
1583                                 s16 ypos = getintfield_default(L, -1, "ypos", 0);
1584                                 u8 prob  = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
1585                                 slice_prob_list.emplace_back(ypos, prob);
1586                         }
1587
1588                         lua_pop(L, 1);
1589                 }
1590         }
1591
1592         if (!schem.getSchematicFromMap(map, p1, p2)) {
1593                 errorstream << "create_schematic: failed to get schematic "
1594                         "from map" << std::endl;
1595                 return 0;
1596         }
1597
1598         schem.applyProbabilities(p1, &prob_list, &slice_prob_list);
1599
1600         schem.saveSchematicToFile(filename, ndef);
1601         actionstream << "create_schematic: saved schematic file '"
1602                 << filename << "'." << std::endl;
1603
1604         lua_pushboolean(L, true);
1605         return 1;
1606 }
1607
1608
1609 // place_schematic(p, schematic, rotation,
1610 //     replacements, force_placement, flagstring)
1611 int ModApiMapgen::l_place_schematic(lua_State *L)
1612 {
1613         MAP_LOCK_REQUIRED;
1614
1615         GET_ENV_PTR;
1616
1617         ServerMap *map = &(env->getServerMap());
1618         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1619
1620         //// Read position
1621         v3s16 p = check_v3s16(L, 1);
1622
1623         //// Read rotation
1624         int rot = ROTATE_0;
1625         std::string enumstr = readParam<std::string>(L, 3, "");
1626         if (!enumstr.empty())
1627                 string_to_enum(es_Rotation, rot, enumstr);
1628
1629         //// Read force placement
1630         bool force_placement = true;
1631         if (lua_isboolean(L, 5))
1632                 force_placement = readParam<bool>(L, 5);
1633
1634         //// Read node replacements
1635         StringMap replace_names;
1636         if (lua_istable(L, 4))
1637                 read_schematic_replacements(L, 4, &replace_names);
1638
1639         //// Read schematic
1640         Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names);
1641         if (!schem) {
1642                 errorstream << "place_schematic: failed to get schematic" << std::endl;
1643                 return 0;
1644         }
1645
1646         //// Read flags
1647         u32 flags = 0;
1648         read_flags(L, 6, flagdesc_deco, &flags, NULL);
1649
1650         schem->placeOnMap(map, p, flags, (Rotation)rot, force_placement);
1651
1652         lua_pushboolean(L, true);
1653         return 1;
1654 }
1655
1656
1657 // place_schematic_on_vmanip(vm, p, schematic, rotation,
1658 //     replacements, force_placement, flagstring)
1659 int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L)
1660 {
1661         NO_MAP_LOCK_REQUIRED;
1662
1663         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1664
1665         //// Read VoxelManip object
1666         MMVManip *vm = LuaVoxelManip::checkobject(L, 1)->vm;
1667
1668         //// Read position
1669         v3s16 p = check_v3s16(L, 2);
1670
1671         //// Read rotation
1672         int rot = ROTATE_0;
1673         std::string enumstr = readParam<std::string>(L, 4, "");
1674         if (!enumstr.empty())
1675                 string_to_enum(es_Rotation, rot, std::string(enumstr));
1676
1677         //// Read force placement
1678         bool force_placement = true;
1679         if (lua_isboolean(L, 6))
1680                 force_placement = readParam<bool>(L, 6);
1681
1682         //// Read node replacements
1683         StringMap replace_names;
1684         if (lua_istable(L, 5))
1685                 read_schematic_replacements(L, 5, &replace_names);
1686
1687         //// Read schematic
1688         Schematic *schem = get_or_load_schematic(L, 3, schemmgr, &replace_names);
1689         if (!schem) {
1690                 errorstream << "place_schematic: failed to get schematic" << std::endl;
1691                 return 0;
1692         }
1693
1694         //// Read flags
1695         u32 flags = 0;
1696         read_flags(L, 7, flagdesc_deco, &flags, NULL);
1697
1698         bool schematic_did_fit = schem->placeOnVManip(
1699                 vm, p, flags, (Rotation)rot, force_placement);
1700
1701         lua_pushboolean(L, schematic_did_fit);
1702         return 1;
1703 }
1704
1705
1706 // serialize_schematic(schematic, format, options={...})
1707 int ModApiMapgen::l_serialize_schematic(lua_State *L)
1708 {
1709         NO_MAP_LOCK_REQUIRED;
1710
1711         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1712
1713         //// Read options
1714         bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false);
1715         u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0);
1716
1717         //// Get schematic
1718         bool was_loaded = false;
1719         Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr);
1720         if (!schem) {
1721                 schem = load_schematic(L, 1, NULL, NULL);
1722                 was_loaded = true;
1723         }
1724         if (!schem) {
1725                 errorstream << "serialize_schematic: failed to get schematic" << std::endl;
1726                 return 0;
1727         }
1728
1729         //// Read format of definition to save as
1730         int schem_format = SCHEM_FMT_MTS;
1731         std::string enumstr = readParam<std::string>(L, 2, "");
1732         if (!enumstr.empty())
1733                 string_to_enum(es_SchematicFormatType, schem_format, enumstr);
1734
1735         //// Serialize to binary string
1736         std::ostringstream os(std::ios_base::binary);
1737         switch (schem_format) {
1738         case SCHEM_FMT_MTS:
1739                 schem->serializeToMts(&os, schem->m_nodenames);
1740                 break;
1741         case SCHEM_FMT_LUA:
1742                 schem->serializeToLua(&os, schem->m_nodenames,
1743                         use_comments, indent_spaces);
1744                 break;
1745         default:
1746                 return 0;
1747         }
1748
1749         if (was_loaded)
1750                 delete schem;
1751
1752         std::string ser = os.str();
1753         lua_pushlstring(L, ser.c_str(), ser.length());
1754         return 1;
1755 }
1756
1757
1758 void ModApiMapgen::Initialize(lua_State *L, int top)
1759 {
1760         API_FCT(get_biome_id);
1761         API_FCT(get_biome_name);
1762         API_FCT(get_heat);
1763         API_FCT(get_humidity);
1764         API_FCT(get_biome_data);
1765         API_FCT(get_mapgen_object);
1766         API_FCT(get_spawn_level);
1767
1768         API_FCT(get_mapgen_params);
1769         API_FCT(set_mapgen_params);
1770         API_FCT(get_mapgen_setting);
1771         API_FCT(set_mapgen_setting);
1772         API_FCT(get_mapgen_setting_noiseparams);
1773         API_FCT(set_mapgen_setting_noiseparams);
1774         API_FCT(set_noiseparams);
1775         API_FCT(get_noiseparams);
1776         API_FCT(set_gen_notify);
1777         API_FCT(get_gen_notify);
1778         API_FCT(get_decoration_id);
1779
1780         API_FCT(register_biome);
1781         API_FCT(register_decoration);
1782         API_FCT(register_ore);
1783         API_FCT(register_schematic);
1784
1785         API_FCT(clear_registered_biomes);
1786         API_FCT(clear_registered_decorations);
1787         API_FCT(clear_registered_ores);
1788         API_FCT(clear_registered_schematics);
1789
1790         API_FCT(generate_ores);
1791         API_FCT(generate_decorations);
1792         API_FCT(create_schematic);
1793         API_FCT(place_schematic);
1794         API_FCT(place_schematic_on_vmanip);
1795         API_FCT(serialize_schematic);
1796 }