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