]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_mapgen.cpp
Fix compiler warning about sign comparison
[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 "util/serialize.h"
26 #include "server.h"
27 #include "environment.h"
28 #include "emerge.h"
29 #include "mg_biome.h"
30 #include "mg_ore.h"
31 #include "mg_decoration.h"
32 #include "mg_schematic.h"
33 #include "mapgen_v5.h"
34 #include "mapgen_v7.h"
35 #include "filesys.h"
36 #include "settings.h"
37 #include "log.h"
38
39 struct EnumString ModApiMapgen::es_BiomeTerrainType[] =
40 {
41         {BIOME_NORMAL, "normal"},
42         {BIOME_LIQUID, "liquid"},
43         {BIOME_NETHER, "nether"},
44         {BIOME_AETHER, "aether"},
45         {BIOME_FLAT,   "flat"},
46         {0, NULL},
47 };
48
49 struct EnumString ModApiMapgen::es_DecorationType[] =
50 {
51         {DECO_SIMPLE,    "simple"},
52         {DECO_SCHEMATIC, "schematic"},
53         {DECO_LSYSTEM,   "lsystem"},
54         {0, NULL},
55 };
56
57 struct EnumString ModApiMapgen::es_MapgenObject[] =
58 {
59         {MGOBJ_VMANIP,    "voxelmanip"},
60         {MGOBJ_HEIGHTMAP, "heightmap"},
61         {MGOBJ_BIOMEMAP,  "biomemap"},
62         {MGOBJ_HEATMAP,   "heatmap"},
63         {MGOBJ_HUMIDMAP,  "humiditymap"},
64         {MGOBJ_GENNOTIFY, "gennotify"},
65         {0, NULL},
66 };
67
68 struct EnumString ModApiMapgen::es_OreType[] =
69 {
70         {ORE_SCATTER, "scatter"},
71         {ORE_SHEET,   "sheet"},
72         {ORE_BLOB,    "blob"},
73         {ORE_VEIN,    "vein"},
74         {0, NULL},
75 };
76
77 struct EnumString ModApiMapgen::es_Rotation[] =
78 {
79         {ROTATE_0,    "0"},
80         {ROTATE_90,   "90"},
81         {ROTATE_180,  "180"},
82         {ROTATE_270,  "270"},
83         {ROTATE_RAND, "random"},
84         {0, NULL},
85 };
86
87 struct EnumString ModApiMapgen::es_SchematicFormatType[] =
88 {
89         {SCHEM_FMT_HANDLE, "handle"},
90         {SCHEM_FMT_MTS,    "mts"},
91         {SCHEM_FMT_LUA,    "lua"},
92         {0, NULL},
93 };
94
95 ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr);
96
97 Biome *get_or_load_biome(lua_State *L, int index,
98         BiomeManager *biomemgr);
99 Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef);
100 size_t get_biome_list(lua_State *L, int index,
101         BiomeManager *biomemgr, std::set<u8> *biome_id_list);
102
103 Schematic *get_or_load_schematic(lua_State *L, int index,
104         SchematicManager *schemmgr, StringMap *replace_names);
105 Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef,
106         StringMap *replace_names);
107 Schematic *load_schematic_from_def(lua_State *L, int index,
108         INodeDefManager *ndef, StringMap *replace_names);
109 bool read_schematic_def(lua_State *L, int index,
110         Schematic *schem, std::vector<std::string> *names);
111
112 bool read_deco_simple(lua_State *L, DecoSimple *deco);
113 bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco);
114
115
116 ///////////////////////////////////////////////////////////////////////////////
117
118 ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr)
119 {
120         if (index < 0)
121                 index = lua_gettop(L) + 1 + index;
122
123         // If a number, assume this is a handle to an object def
124         if (lua_isnumber(L, index))
125                 return objmgr->get(lua_tointeger(L, index));
126
127         // If a string, assume a name is given instead
128         if (lua_isstring(L, index))
129                 return objmgr->getByName(lua_tostring(L, index));
130
131         return NULL;
132 }
133
134 ///////////////////////////////////////////////////////////////////////////////
135
136 Schematic *get_or_load_schematic(lua_State *L, int index,
137         SchematicManager *schemmgr, StringMap *replace_names)
138 {
139         if (index < 0)
140                 index = lua_gettop(L) + 1 + index;
141
142         Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr);
143         if (schem)
144                 return schem;
145
146         schem = load_schematic(L, index, schemmgr->getNodeDef(),
147                 replace_names);
148         if (!schem)
149                 return NULL;
150
151         if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) {
152                 delete schem;
153                 return NULL;
154         }
155
156         return schem;
157 }
158
159
160 Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef,
161         StringMap *replace_names)
162 {
163         if (index < 0)
164                 index = lua_gettop(L) + 1 + index;
165
166         Schematic *schem = NULL;
167
168         if (lua_istable(L, index)) {
169                 schem = load_schematic_from_def(L, index, ndef,
170                         replace_names);
171                 if (!schem) {
172                         delete schem;
173                         return NULL;
174                 }
175         } else if (lua_isnumber(L, index)) {
176                 return NULL;
177         } else if (lua_isstring(L, index)) {
178                 schem = SchematicManager::create(SCHEMATIC_NORMAL);
179
180                 std::string filepath = lua_tostring(L, index);
181                 if (!fs::IsPathAbsolute(filepath))
182                         filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath;
183
184                 if (!schem->loadSchematicFromFile(filepath, ndef,
185                                 replace_names)) {
186                         delete schem;
187                         return NULL;
188                 }
189         }
190
191         return schem;
192 }
193
194
195 Schematic *load_schematic_from_def(lua_State *L, int index,
196         INodeDefManager *ndef, StringMap *replace_names)
197 {
198         Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL);
199
200         if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) {
201                 delete schem;
202                 return NULL;
203         }
204
205         size_t num_nodes = schem->m_nodenames.size();
206
207         schem->m_nnlistsizes.push_back(num_nodes);
208
209         if (replace_names) {
210                 for (size_t i = 0; i != num_nodes; i++) {
211                         StringMap::iterator it = replace_names->find(schem->m_nodenames[i]);
212                         if (it != replace_names->end())
213                                 schem->m_nodenames[i] = it->second;
214                 }
215         }
216
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::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::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                         replace_from = lua_tostring(L, -1);
326                         lua_pop(L, 1);
327
328                         lua_rawgeti(L, -1, 2);
329                         replace_to = lua_tostring(L, -1);
330                         lua_pop(L, 1);
331                 } else { // New {x = "y", ...} format
332                         replace_from = lua_tostring(L, -2);
333                         replace_to = lua_tostring(L, -1);
334                 }
335
336                 replace_names->insert(std::make_pair(replace_from, replace_to));
337                 lua_pop(L, 1);
338         }
339 }
340
341 ///////////////////////////////////////////////////////////////////////////////
342
343 Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr)
344 {
345         if (index < 0)
346                 index = lua_gettop(L) + 1 + index;
347
348         Biome *biome = (Biome *)get_objdef(L, index, biomemgr);
349         if (biome)
350                 return biome;
351
352         biome = read_biome_def(L, index, biomemgr->getNodeDef());
353         if (!biome)
354                 return NULL;
355
356         if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) {
357                 delete biome;
358                 return NULL;
359         }
360
361         return biome;
362 }
363
364
365 Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef)
366 {
367         if (!lua_istable(L, index))
368                 return NULL;
369
370         BiomeType biometype = (BiomeType)getenumfield(L, index, "type",
371                 ModApiMapgen::es_BiomeTerrainType, BIOME_NORMAL);
372         Biome *b = BiomeManager::create(biometype);
373
374         b->name            = getstringfield_default(L, index, "name", "");
375         b->depth_top       = getintfield_default(L,    index, "depth_top",       1);
376         b->depth_filler    = getintfield_default(L,    index, "depth_filler",    2);
377         b->depth_water_top = getintfield_default(L,    index, "depth_water_top", 0);
378         b->y_min           = getintfield_default(L,    index, "y_min",           -31000);
379         b->y_max           = getintfield_default(L,    index, "y_max",           31000);
380         b->heat_point      = getfloatfield_default(L,  index, "heat_point",      0.f);
381         b->humidity_point  = getfloatfield_default(L,  index, "humidity_point",  0.f);
382         b->flags           = 0; //reserved
383
384         std::vector<std::string> &nn = b->m_nodenames;
385         nn.push_back(getstringfield_default(L, index, "node_top",         ""));
386         nn.push_back(getstringfield_default(L, index, "node_filler",      ""));
387         nn.push_back(getstringfield_default(L, index, "node_stone",       ""));
388         nn.push_back(getstringfield_default(L, index, "node_water_top",   ""));
389         nn.push_back(getstringfield_default(L, index, "node_water",       ""));
390         nn.push_back(getstringfield_default(L, index, "node_river_water", ""));
391         nn.push_back(getstringfield_default(L, index, "node_dust",        ""));
392         ndef->pendNodeResolve(b);
393
394         return b;
395 }
396
397
398 size_t get_biome_list(lua_State *L, int index,
399         BiomeManager *biomemgr, std::set<u8> *biome_id_list)
400 {
401         if (index < 0)
402                 index = lua_gettop(L) + 1 + index;
403
404         if (lua_isnil(L, index))
405                 return 0;
406
407         bool is_single = true;
408         if (lua_istable(L, index)) {
409                 lua_getfield(L, index, "name");
410                 is_single = !lua_isnil(L, -1);
411                 lua_pop(L, 1);
412         }
413
414         if (is_single) {
415                 Biome *biome = get_or_load_biome(L, index, biomemgr);
416                 if (!biome) {
417                         errorstream << "get_biome_list: failed to get biome" << std::endl;
418                         return 1;
419                 }
420
421                 biome_id_list->insert(biome->index);
422                 return 0;
423         }
424
425         // returns number of failed resolutions
426         size_t fail_count = 0;
427         size_t count = 0;
428
429         for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) {
430                 count++;
431                 Biome *biome = get_or_load_biome(L, -1, biomemgr);
432                 if (!biome) {
433                         fail_count++;
434                         errorstream << "get_biome_list: failed to load biome (index "
435                                 << count << ")" << std::endl;
436                         continue;
437                 }
438
439                 biome_id_list->insert(biome->index);
440         }
441
442         return fail_count;
443 }
444
445 ///////////////////////////////////////////////////////////////////////////////
446
447 // get_mapgen_object(objectname)
448 // returns the requested object used during map generation
449 int ModApiMapgen::l_get_mapgen_object(lua_State *L)
450 {
451         const char *mgobjstr = lua_tostring(L, 1);
452
453         int mgobjint;
454         if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
455                 return 0;
456
457         enum MapgenObject mgobj = (MapgenObject)mgobjint;
458
459         EmergeManager *emerge = getServer(L)->getEmergeManager();
460         Mapgen *mg = emerge->getCurrentMapgen();
461         if (!mg)
462                 return 0;
463
464         size_t maplen = mg->csize.X * mg->csize.Z;
465
466         switch (mgobj) {
467         case MGOBJ_VMANIP: {
468                 MMVManip *vm = mg->vm;
469
470                 // VoxelManip object
471                 LuaVoxelManip *o = new LuaVoxelManip(vm, true);
472                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
473                 luaL_getmetatable(L, "VoxelManip");
474                 lua_setmetatable(L, -2);
475
476                 // emerged min pos
477                 push_v3s16(L, vm->m_area.MinEdge);
478
479                 // emerged max pos
480                 push_v3s16(L, vm->m_area.MaxEdge);
481
482                 return 3;
483         }
484         case MGOBJ_HEIGHTMAP: {
485                 if (!mg->heightmap)
486                         return 0;
487
488                 lua_newtable(L);
489                 for (size_t i = 0; i != maplen; i++) {
490                         lua_pushinteger(L, mg->heightmap[i]);
491                         lua_rawseti(L, -2, i + 1);
492                 }
493
494                 return 1;
495         }
496         case MGOBJ_BIOMEMAP: {
497                 if (!mg->biomemap)
498                         return 0;
499
500                 lua_newtable(L);
501                 for (size_t i = 0; i != maplen; i++) {
502                         lua_pushinteger(L, mg->biomemap[i]);
503                         lua_rawseti(L, -2, i + 1);
504                 }
505
506                 return 1;
507         }
508         case MGOBJ_HEATMAP: { // Mapgen V7 specific objects
509         case MGOBJ_HUMIDMAP:
510                 if (strcmp(emerge->params.mg_name.c_str(), "v7"))
511                         return 0;
512
513                 MapgenV7 *mgv7 = (MapgenV7 *)mg;
514
515                 float *arr = (mgobj == MGOBJ_HEATMAP) ?
516                         mgv7->noise_heat->result : mgv7->noise_humidity->result;
517                 if (!arr)
518                         return 0;
519
520                 lua_newtable(L);
521                 for (size_t i = 0; i != maplen; i++) {
522                         lua_pushnumber(L, arr[i]);
523                         lua_rawseti(L, -2, i + 1);
524                 }
525
526                 return 1;
527         }
528         case MGOBJ_GENNOTIFY: {
529                 std::map<std::string, std::vector<v3s16> >event_map;
530                 std::map<std::string, std::vector<v3s16> >::iterator it;
531
532                 mg->gennotify.getEvents(event_map);
533
534                 lua_newtable(L);
535                 for (it = event_map.begin(); it != event_map.end(); ++it) {
536                         lua_newtable(L);
537
538                         for (size_t j = 0; j != it->second.size(); j++) {
539                                 push_v3s16(L, it->second[j]);
540                                 lua_rawseti(L, -2, j + 1);
541                         }
542
543                         lua_setfield(L, -2, it->first.c_str());
544                 }
545
546                 return 1;
547         }
548         }
549
550         return 0;
551 }
552
553
554 int ModApiMapgen::l_get_mapgen_params(lua_State *L)
555 {
556         MapgenParams *params = &getServer(L)->getEmergeManager()->params;
557
558         lua_newtable(L);
559
560         lua_pushstring(L, params->mg_name.c_str());
561         lua_setfield(L, -2, "mgname");
562
563         lua_pushinteger(L, params->seed);
564         lua_setfield(L, -2, "seed");
565
566         lua_pushinteger(L, params->water_level);
567         lua_setfield(L, -2, "water_level");
568
569         lua_pushinteger(L, params->chunksize);
570         lua_setfield(L, -2, "chunksize");
571
572         std::string flagstr = writeFlagString(params->flags, flagdesc_mapgen, (u32)-1);
573         lua_pushstring(L, flagstr.c_str());
574         lua_setfield(L, -2, "flags");
575
576         return 1;
577 }
578
579
580 // set_mapgen_params(params)
581 // set mapgen parameters
582 int ModApiMapgen::l_set_mapgen_params(lua_State *L)
583 {
584         if (!lua_istable(L, 1))
585                 return 0;
586
587         MapgenParams *params = &getServer(L)->getEmergeManager()->params;
588         u32 flags = 0, flagmask = 0;
589
590         lua_getfield(L, 1, "mgname");
591         if (lua_isstring(L, -1)) {
592                 params->mg_name = lua_tostring(L, -1);
593                 delete params->sparams;
594                 params->sparams = NULL;
595         }
596
597         lua_getfield(L, 1, "seed");
598         if (lua_isnumber(L, -1))
599                 params->seed = lua_tointeger(L, -1);
600
601         lua_getfield(L, 1, "water_level");
602         if (lua_isnumber(L, -1))
603                 params->water_level = lua_tointeger(L, -1);
604
605         warn_if_field_exists(L, 1, "flagmask",
606                 "Deprecated: flags field now includes unset flags.");
607         lua_getfield(L, 1, "flagmask");
608         if (lua_isstring(L, -1))
609                 params->flags &= ~readFlagString(lua_tostring(L, -1), flagdesc_mapgen, NULL);
610
611         if (getflagsfield(L, 1, "flags", flagdesc_mapgen, &flags, &flagmask)) {
612                 params->flags &= ~flagmask;
613                 params->flags |= flags;
614         }
615
616         return 0;
617 }
618
619
620 // set_noiseparams(name, noiseparams, set_default)
621 // set global config values for noise parameters
622 int ModApiMapgen::l_set_noiseparams(lua_State *L)
623 {
624         const char *name = luaL_checkstring(L, 1);
625
626         NoiseParams np;
627         if (!read_noiseparams(L, 2, &np))
628                 return 0;
629
630         bool set_default = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : true;
631
632         g_settings->setNoiseParams(name, np, set_default);
633
634         return 0;
635 }
636
637
638 // set_gen_notify(flags, {deco_id_table})
639 int ModApiMapgen::l_set_gen_notify(lua_State *L)
640 {
641         u32 flags = 0, flagmask = 0;
642         EmergeManager *emerge = getServer(L)->getEmergeManager();
643
644         if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) {
645                 emerge->gen_notify_on &= ~flagmask;
646                 emerge->gen_notify_on |= flags;
647         }
648
649         if (lua_istable(L, 2)) {
650                 lua_pushnil(L);
651                 while (lua_next(L, 2)) {
652                         if (lua_isnumber(L, -1))
653                                 emerge->gen_notify_on_deco_ids.insert(lua_tonumber(L, -1));
654                         lua_pop(L, 1);
655                 }
656         }
657
658         return 0;
659 }
660
661
662 // register_biome({lots of stuff})
663 int ModApiMapgen::l_register_biome(lua_State *L)
664 {
665         int index = 1;
666         luaL_checktype(L, index, LUA_TTABLE);
667
668         INodeDefManager *ndef = getServer(L)->getNodeDefManager();
669         BiomeManager *bmgr    = getServer(L)->getEmergeManager()->biomemgr;
670
671         Biome *biome = read_biome_def(L, index, ndef);
672         if (!biome)
673                 return 0;
674
675         ObjDefHandle handle = bmgr->add(biome);
676         if (handle == OBJDEF_INVALID_HANDLE) {
677                 delete biome;
678                 return 0;
679         }
680
681         lua_pushinteger(L, handle);
682         return 1;
683 }
684
685
686 // register_decoration({lots of stuff})
687 int ModApiMapgen::l_register_decoration(lua_State *L)
688 {
689         int index = 1;
690         luaL_checktype(L, index, LUA_TTABLE);
691
692         INodeDefManager *ndef      = getServer(L)->getNodeDefManager();
693         DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr;
694         BiomeManager *biomemgr     = getServer(L)->getEmergeManager()->biomemgr;
695         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
696
697         enum DecorationType decotype = (DecorationType)getenumfield(L, index,
698                                 "deco_type", es_DecorationType, -1);
699
700         Decoration *deco = decomgr->create(decotype);
701         if (!deco) {
702                 errorstream << "register_decoration: decoration placement type "
703                         << decotype << " not implemented" << std::endl;
704                 return 0;
705         }
706
707         deco->name       = getstringfield_default(L, index, "name", "");
708         deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02);
709         deco->y_min      = getintfield_default(L, index, "y_min", -31000);
710         deco->y_max      = getintfield_default(L, index, "y_max", 31000);
711         deco->sidelen    = getintfield_default(L, index, "sidelen", 8);
712         if (deco->sidelen <= 0) {
713                 errorstream << "register_decoration: sidelen must be "
714                         "greater than 0" << std::endl;
715                 delete deco;
716                 return 0;
717         }
718
719         //// Get node name(s) to place decoration on
720         size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames);
721         deco->m_nnlistsizes.push_back(nread);
722
723         //// Get decoration flags
724         getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL);
725
726         //// Get NoiseParams to define how decoration is placed
727         lua_getfield(L, index, "noise_params");
728         if (read_noiseparams(L, -1, &deco->np))
729                 deco->flags |= DECO_USE_NOISE;
730         lua_pop(L, 1);
731
732         //// Get biomes associated with this decoration (if any)
733         lua_getfield(L, index, "biomes");
734         if (get_biome_list(L, -1, biomemgr, &deco->biomes))
735                 errorstream << "register_decoration: couldn't get all biomes " << std::endl;
736         lua_pop(L, 1);
737
738         //// Handle decoration type-specific parameters
739         bool success = false;
740         switch (decotype) {
741         case DECO_SIMPLE:
742                 success = read_deco_simple(L, (DecoSimple *)deco);
743                 break;
744         case DECO_SCHEMATIC:
745                 success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco);
746                 break;
747         case DECO_LSYSTEM:
748                 break;
749         }
750
751         if (!success) {
752                 delete deco;
753                 return 0;
754         }
755
756         ndef->pendNodeResolve(deco);
757
758         ObjDefHandle handle = decomgr->add(deco);
759         if (handle == OBJDEF_INVALID_HANDLE) {
760                 delete deco;
761                 return 0;
762         }
763
764         lua_pushinteger(L, handle);
765         return 1;
766 }
767
768
769 bool read_deco_simple(lua_State *L, DecoSimple *deco)
770 {
771         size_t nnames;
772         int index = 1;
773
774         deco->deco_height     = getintfield_default(L, index, "height", 1);
775         deco->deco_height_max = getintfield_default(L, index, "height_max", 0);
776         deco->nspawnby        = getintfield_default(L, index, "num_spawn_by", -1);
777
778         if (deco->deco_height <= 0) {
779                 errorstream << "register_decoration: simple decoration height"
780                         " must be greater than 0" << std::endl;
781                 return false;
782         }
783
784         nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames);
785         deco->m_nnlistsizes.push_back(nnames);
786         if (nnames == 0) {
787                 errorstream << "register_decoration: no decoration nodes "
788                         "defined" << std::endl;
789                 return false;
790         }
791
792         nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames);
793         deco->m_nnlistsizes.push_back(nnames);
794         if (nnames == 0 && deco->nspawnby != -1) {
795                 errorstream << "register_decoration: no spawn_by nodes defined,"
796                         " but num_spawn_by specified" << std::endl;
797                 return false;
798         }
799
800         return true;
801 }
802
803
804 bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco)
805 {
806         int index = 1;
807
808         deco->rotation = (Rotation)getenumfield(L, index, "rotation",
809                 ModApiMapgen::es_Rotation, ROTATE_0);
810
811         StringMap replace_names;
812         lua_getfield(L, index, "replacements");
813         if (lua_istable(L, -1))
814                 read_schematic_replacements(L, -1, &replace_names);
815         lua_pop(L, 1);
816
817         lua_getfield(L, index, "schematic");
818         Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names);
819         lua_pop(L, 1);
820
821         deco->schematic = schem;
822         return schem != NULL;
823 }
824
825
826 // register_ore({lots of stuff})
827 int ModApiMapgen::l_register_ore(lua_State *L)
828 {
829         int index = 1;
830         luaL_checktype(L, index, LUA_TTABLE);
831
832         INodeDefManager *ndef = getServer(L)->getNodeDefManager();
833         BiomeManager *bmgr    = getServer(L)->getEmergeManager()->biomemgr;
834         OreManager *oremgr    = getServer(L)->getEmergeManager()->oremgr;
835
836         enum OreType oretype = (OreType)getenumfield(L, index,
837                                 "ore_type", es_OreType, ORE_SCATTER);
838         Ore *ore = oremgr->create(oretype);
839         if (!ore) {
840                 errorstream << "register_ore: ore_type " << oretype << " not implemented";
841                 return 0;
842         }
843
844         ore->name           = getstringfield_default(L, index, "name", "");
845         ore->ore_param2     = (u8)getintfield_default(L, index, "ore_param2", 0);
846         ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1);
847         ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1);
848         ore->clust_size     = getintfield_default(L, index, "clust_size", 0);
849         ore->nthresh        = getfloatfield_default(L, index, "noise_threshhold", 0);
850         ore->noise          = NULL;
851         ore->flags          = 0;
852
853         //// Get y_min/y_max
854         warn_if_field_exists(L, index, "height_min",
855                 "Deprecated: new name is \"y_min\".");
856         warn_if_field_exists(L, index, "height_max",
857                 "Deprecated: new name is \"y_max\".");
858
859         int ymin, ymax;
860         if (!getintfield(L, index, "y_min", ymin) &&
861                 !getintfield(L, index, "height_min", ymin))
862                 ymin = -31000;
863         if (!getintfield(L, index, "y_max", ymax) &&
864                 !getintfield(L, index, "height_max", ymax))
865                 ymax = 31000;
866         ore->y_min = ymin;
867         ore->y_max = ymax;
868
869         if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) {
870                 errorstream << "register_ore: clust_scarcity and clust_num_ores"
871                         "must be greater than 0" << std::endl;
872                 delete ore;
873                 return 0;
874         }
875
876         //// Get flags
877         getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL);
878
879         //// Get biomes associated with this decoration (if any)
880         lua_getfield(L, index, "biomes");
881         if (get_biome_list(L, -1, bmgr, &ore->biomes))
882                 errorstream << "register_ore: couldn't get all biomes " << std::endl;
883         lua_pop(L, 1);
884
885         //// Get noise parameters if needed
886         lua_getfield(L, index, "noise_params");
887         if (read_noiseparams(L, -1, &ore->np)) {
888                 ore->flags |= OREFLAG_USE_NOISE;
889         } else if (ore->NEEDS_NOISE) {
890                 errorstream << "register_ore: specified ore type requires valid "
891                         "noise parameters" << std::endl;
892                 delete ore;
893                 return 0;
894         }
895         lua_pop(L, 1);
896
897         if (oretype == ORE_VEIN) {
898                 OreVein *orevein = (OreVein *)ore;
899                 orevein->random_factor = getfloatfield_default(L, index,
900                         "random_factor", 1.f);
901         }
902
903         ObjDefHandle handle = oremgr->add(ore);
904         if (handle == OBJDEF_INVALID_HANDLE) {
905                 delete ore;
906                 return 0;
907         }
908
909         ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", ""));
910
911         size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames);
912         ore->m_nnlistsizes.push_back(nnames);
913
914         ndef->pendNodeResolve(ore);
915
916         lua_pushinteger(L, handle);
917         return 1;
918 }
919
920
921 // register_schematic({schematic}, replacements={})
922 int ModApiMapgen::l_register_schematic(lua_State *L)
923 {
924         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
925
926         StringMap replace_names;
927         if (lua_istable(L, 2))
928                 read_schematic_replacements(L, 2, &replace_names);
929
930         Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(),
931                 &replace_names);
932         if (!schem)
933                 return 0;
934
935         ObjDefHandle handle = schemmgr->add(schem);
936         if (handle == OBJDEF_INVALID_HANDLE) {
937                 delete schem;
938                 return 0;
939         }
940
941         lua_pushinteger(L, handle);
942         return 1;
943 }
944
945
946 // clear_registered_biomes()
947 int ModApiMapgen::l_clear_registered_biomes(lua_State *L)
948 {
949         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
950         bmgr->clear();
951         return 0;
952 }
953
954
955 // clear_registered_decorations()
956 int ModApiMapgen::l_clear_registered_decorations(lua_State *L)
957 {
958         DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr;
959         dmgr->clear();
960         return 0;
961 }
962
963
964 // clear_registered_ores()
965 int ModApiMapgen::l_clear_registered_ores(lua_State *L)
966 {
967         OreManager *omgr = getServer(L)->getEmergeManager()->oremgr;
968         omgr->clear();
969         return 0;
970 }
971
972
973 // clear_registered_schematics()
974 int ModApiMapgen::l_clear_registered_schematics(lua_State *L)
975 {
976         SchematicManager *smgr = getServer(L)->getEmergeManager()->schemmgr;
977         smgr->clear();
978         return 0;
979 }
980
981
982 // generate_ores(vm, p1, p2, [ore_id])
983 int ModApiMapgen::l_generate_ores(lua_State *L)
984 {
985         EmergeManager *emerge = getServer(L)->getEmergeManager();
986
987         Mapgen mg;
988         mg.seed = emerge->params.seed;
989         mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
990         mg.ndef = getServer(L)->getNodeDefManager();
991
992         v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
993                         mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
994         v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
995                         mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
996         sortBoxVerticies(pmin, pmax);
997
998         u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);
999
1000         emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax);
1001
1002         return 0;
1003 }
1004
1005
1006 // generate_decorations(vm, p1, p2, [deco_id])
1007 int ModApiMapgen::l_generate_decorations(lua_State *L)
1008 {
1009         EmergeManager *emerge = getServer(L)->getEmergeManager();
1010
1011         Mapgen mg;
1012         mg.seed = emerge->params.seed;
1013         mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
1014         mg.ndef = getServer(L)->getNodeDefManager();
1015
1016         v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
1017                         mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
1018         v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
1019                         mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
1020         sortBoxVerticies(pmin, pmax);
1021
1022         u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);
1023
1024         emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax);
1025
1026         return 0;
1027 }
1028
1029
1030 // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list)
1031 int ModApiMapgen::l_create_schematic(lua_State *L)
1032 {
1033         INodeDefManager *ndef = getServer(L)->getNodeDefManager();
1034         Map *map = &(getEnv(L)->getMap());
1035         Schematic schem;
1036
1037         v3s16 p1 = check_v3s16(L, 1);
1038         v3s16 p2 = check_v3s16(L, 2);
1039         sortBoxVerticies(p1, p2);
1040
1041         std::vector<std::pair<v3s16, u8> > prob_list;
1042         if (lua_istable(L, 3)) {
1043                 lua_pushnil(L);
1044                 while (lua_next(L, 3)) {
1045                         if (lua_istable(L, -1)) {
1046                                 lua_getfield(L, -1, "pos");
1047                                 v3s16 pos = check_v3s16(L, -1);
1048                                 lua_pop(L, 1);
1049
1050                                 u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
1051                                 prob_list.push_back(std::make_pair(pos, prob));
1052                         }
1053
1054                         lua_pop(L, 1);
1055                 }
1056         }
1057
1058         std::vector<std::pair<s16, u8> > slice_prob_list;
1059         if (lua_istable(L, 5)) {
1060                 lua_pushnil(L);
1061                 while (lua_next(L, 5)) {
1062                         if (lua_istable(L, -1)) {
1063                                 s16 ypos = getintfield_default(L, -1, "ypos", 0);
1064                                 u8 prob  = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
1065                                 slice_prob_list.push_back(std::make_pair(ypos, prob));
1066                         }
1067
1068                         lua_pop(L, 1);
1069                 }
1070         }
1071
1072         const char *filename = luaL_checkstring(L, 4);
1073
1074         if (!schem.getSchematicFromMap(map, p1, p2)) {
1075                 errorstream << "create_schematic: failed to get schematic "
1076                         "from map" << std::endl;
1077                 return 0;
1078         }
1079
1080         schem.applyProbabilities(p1, &prob_list, &slice_prob_list);
1081
1082         schem.saveSchematicToFile(filename, ndef);
1083         actionstream << "create_schematic: saved schematic file '"
1084                 << filename << "'." << std::endl;
1085
1086         lua_pushboolean(L, true);
1087         return 1;
1088 }
1089
1090
1091 // place_schematic(p, schematic, rotation, replacement)
1092 int ModApiMapgen::l_place_schematic(lua_State *L)
1093 {
1094         Map *map = &(getEnv(L)->getMap());
1095         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1096
1097         //// Read position
1098         v3s16 p = check_v3s16(L, 1);
1099
1100         //// Read rotation
1101         int rot = ROTATE_0;
1102         const char *enumstr = lua_tostring(L, 3);
1103         if (enumstr)
1104                 string_to_enum(es_Rotation, rot, std::string(enumstr));
1105
1106         //// Read force placement
1107         bool force_placement = true;
1108         if (lua_isboolean(L, 5))
1109                 force_placement = lua_toboolean(L, 5);
1110
1111         //// Read node replacements
1112         StringMap replace_names;
1113         if (lua_istable(L, 4))
1114                 read_schematic_replacements(L, 4, &replace_names);
1115
1116         //// Read schematic
1117         Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names);
1118         if (!schem) {
1119                 errorstream << "place_schematic: failed to get schematic" << std::endl;
1120                 return 0;
1121         }
1122
1123         schem->placeStructure(map, p, 0, (Rotation)rot, force_placement);
1124
1125         lua_pushboolean(L, true);
1126         return 1;
1127 }
1128
1129 // serialize_schematic(schematic, format, options={...})
1130 int ModApiMapgen::l_serialize_schematic(lua_State *L)
1131 {
1132         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1133
1134         //// Read options
1135         bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false);
1136         u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0);
1137
1138         //// Get schematic
1139         bool was_loaded = false;
1140         Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr);
1141         if (!schem) {
1142                 schem = load_schematic(L, 1, NULL, NULL);
1143                 was_loaded = true;
1144         }
1145         if (!schem) {
1146                 errorstream << "serialize_schematic: failed to get schematic" << std::endl;
1147                 return 0;
1148         }
1149
1150         //// Read format of definition to save as
1151         int schem_format = SCHEM_FMT_MTS;
1152         const char *enumstr = lua_tostring(L, 2);
1153         if (enumstr)
1154                 string_to_enum(es_SchematicFormatType, schem_format, std::string(enumstr));
1155
1156         //// Serialize to binary string
1157         std::ostringstream os(std::ios_base::binary);
1158         switch (schem_format) {
1159         case SCHEM_FMT_MTS:
1160                 schem->serializeToMts(&os, schem->m_nodenames);
1161                 break;
1162         case SCHEM_FMT_LUA:
1163                 schem->serializeToLua(&os, schem->m_nodenames,
1164                         use_comments, indent_spaces);
1165                 break;
1166         default:
1167                 return 0;
1168         }
1169
1170         if (was_loaded)
1171                 delete schem;
1172
1173         std::string ser = os.str();
1174         lua_pushlstring(L, ser.c_str(), ser.length());
1175         return 1;
1176 }
1177
1178
1179 void ModApiMapgen::Initialize(lua_State *L, int top)
1180 {
1181         API_FCT(get_mapgen_object);
1182
1183         API_FCT(get_mapgen_params);
1184         API_FCT(set_mapgen_params);
1185         API_FCT(set_noiseparams);
1186         API_FCT(set_gen_notify);
1187
1188         API_FCT(register_biome);
1189         API_FCT(register_decoration);
1190         API_FCT(register_ore);
1191         API_FCT(register_schematic);
1192
1193         API_FCT(clear_registered_biomes);
1194         API_FCT(clear_registered_decorations);
1195         API_FCT(clear_registered_ores);
1196         API_FCT(clear_registered_schematics);
1197
1198         API_FCT(generate_ores);
1199         API_FCT(generate_decorations);
1200         API_FCT(create_schematic);
1201         API_FCT(place_schematic);
1202         API_FCT(serialize_schematic);
1203 }