]> git.lizzy.rs Git - dragonfireclient.git/blob - src/mapgen/mg_schematic.cpp
Randomwalk caves: Add parameters for number, proportion flooded. Allow small caves...
[dragonfireclient.git] / src / mapgen / mg_schematic.cpp
1 /*
2 Minetest
3 Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
4 Copyright (C) 2015-2018 paramat
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include <fstream>
22 #include <typeinfo>
23 #include "mg_schematic.h"
24 #include "server.h"
25 #include "mapgen.h"
26 #include "emerge.h"
27 #include "map.h"
28 #include "mapblock.h"
29 #include "log.h"
30 #include "util/numeric.h"
31 #include "util/serialize.h"
32 #include "serialization.h"
33 #include "filesys.h"
34 #include "voxelalgorithms.h"
35
36 ///////////////////////////////////////////////////////////////////////////////
37
38
39 SchematicManager::SchematicManager(Server *server) :
40         ObjDefManager(server, OBJDEF_SCHEMATIC),
41         m_server(server)
42 {
43 }
44
45
46 void SchematicManager::clear()
47 {
48         EmergeManager *emerge = m_server->getEmergeManager();
49
50         // Remove all dangling references in Decorations
51         DecorationManager *decomgr = emerge->decomgr;
52         for (size_t i = 0; i != decomgr->getNumObjects(); i++) {
53                 Decoration *deco = (Decoration *)decomgr->getRaw(i);
54
55                 try {
56                         DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco);
57                         if (dschem)
58                                 dschem->schematic = NULL;
59                 } catch (const std::bad_cast &) {
60                 }
61         }
62
63         ObjDefManager::clear();
64 }
65
66
67 ///////////////////////////////////////////////////////////////////////////////
68
69
70 Schematic::Schematic()
71 = default;
72
73
74 Schematic::~Schematic()
75 {
76         delete []schemdata;
77         delete []slice_probs;
78 }
79
80
81 void Schematic::resolveNodeNames()
82 {
83         getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
84
85         size_t bufsize = size.X * size.Y * size.Z;
86         for (size_t i = 0; i != bufsize; i++) {
87                 content_t c_original = schemdata[i].getContent();
88                 content_t c_new = c_nodes[c_original];
89                 schemdata[i].setContent(c_new);
90         }
91 }
92
93
94 void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place)
95 {
96         sanity_check(m_ndef != NULL);
97
98         int xstride = 1;
99         int ystride = size.X;
100         int zstride = size.X * size.Y;
101
102         s16 sx = size.X;
103         s16 sy = size.Y;
104         s16 sz = size.Z;
105
106         int i_start, i_step_x, i_step_z;
107         switch (rot) {
108                 case ROTATE_90:
109                         i_start  = sx - 1;
110                         i_step_x = zstride;
111                         i_step_z = -xstride;
112                         SWAP(s16, sx, sz);
113                         break;
114                 case ROTATE_180:
115                         i_start  = zstride * (sz - 1) + sx - 1;
116                         i_step_x = -xstride;
117                         i_step_z = -zstride;
118                         break;
119                 case ROTATE_270:
120                         i_start  = zstride * (sz - 1);
121                         i_step_x = -zstride;
122                         i_step_z = xstride;
123                         SWAP(s16, sx, sz);
124                         break;
125                 default:
126                         i_start  = 0;
127                         i_step_x = xstride;
128                         i_step_z = zstride;
129         }
130
131         s16 y_map = p.Y;
132         for (s16 y = 0; y != sy; y++) {
133                 if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) &&
134                         (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
135                         continue;
136
137                 for (s16 z = 0; z != sz; z++) {
138                         u32 i = z * i_step_z + y * ystride + i_start;
139                         for (s16 x = 0; x != sx; x++, i += i_step_x) {
140                                 v3s16 pos(p.X + x, y_map, p.Z + z);
141                                 if (!vm->m_area.contains(pos))
142                                         continue;
143
144                                 if (schemdata[i].getContent() == CONTENT_IGNORE)
145                                         continue;
146
147                                 u8 placement_prob     = schemdata[i].param1 & MTSCHEM_PROB_MASK;
148                                 bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
149
150                                 if (placement_prob == MTSCHEM_PROB_NEVER)
151                                         continue;
152
153                                 u32 vi = vm->m_area.index(pos);
154                                 if (!force_place && !force_place_node) {
155                                         content_t c = vm->m_data[vi].getContent();
156                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
157                                                 continue;
158                                 }
159
160                                 if ((placement_prob != MTSCHEM_PROB_ALWAYS) &&
161                                         (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
162                                         continue;
163
164                                 vm->m_data[vi] = schemdata[i];
165                                 vm->m_data[vi].param1 = 0;
166
167                                 if (rot)
168                                         vm->m_data[vi].rotateAlongYAxis(m_ndef, rot);
169                         }
170                 }
171                 y_map++;
172         }
173 }
174
175
176 bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags,
177         Rotation rot, bool force_place)
178 {
179         assert(vm != NULL);
180         assert(schemdata != NULL);
181         sanity_check(m_ndef != NULL);
182
183         //// Determine effective rotation and effective schematic dimensions
184         if (rot == ROTATE_RAND)
185                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
186
187         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
188                 v3s16(size.Z, size.Y, size.X) : size;
189
190         //// Adjust placement position if necessary
191         if (flags & DECO_PLACE_CENTER_X)
192                 p.X -= (s.X - 1) / 2;
193         if (flags & DECO_PLACE_CENTER_Y)
194                 p.Y -= (s.Y - 1) / 2;
195         if (flags & DECO_PLACE_CENTER_Z)
196                 p.Z -= (s.Z - 1) / 2;
197
198         blitToVManip(vm, p, rot, force_place);
199
200         return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1)));
201 }
202
203 void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags,
204         Rotation rot, bool force_place)
205 {
206         std::map<v3s16, MapBlock *> lighting_modified_blocks;
207         std::map<v3s16, MapBlock *> modified_blocks;
208         std::map<v3s16, MapBlock *>::iterator it;
209
210         assert(map != NULL);
211         assert(schemdata != NULL);
212         sanity_check(m_ndef != NULL);
213
214         //// Determine effective rotation and effective schematic dimensions
215         if (rot == ROTATE_RAND)
216                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
217
218         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
219                         v3s16(size.Z, size.Y, size.X) : size;
220
221         //// Adjust placement position if necessary
222         if (flags & DECO_PLACE_CENTER_X)
223                 p.X -= (s.X - 1) / 2;
224         if (flags & DECO_PLACE_CENTER_Y)
225                 p.Y -= (s.Y - 1) / 2;
226         if (flags & DECO_PLACE_CENTER_Z)
227                 p.Z -= (s.Z - 1) / 2;
228
229         //// Create VManip for effected area, emerge our area, modify area
230         //// inside VManip, then blit back.
231         v3s16 bp1 = getNodeBlockPos(p);
232         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1, 1, 1));
233
234         MMVManip vm(map);
235         vm.initialEmerge(bp1, bp2);
236
237         blitToVManip(&vm, p, rot, force_place);
238
239         voxalgo::blit_back_with_light(map, &vm, &modified_blocks);
240
241         //// Carry out post-map-modification actions
242
243         //// Create & dispatch map modification events to observers
244         MapEditEvent event;
245         event.type = MEET_OTHER;
246         for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it)
247                 event.modified_blocks.insert(it->first);
248
249         map->dispatchEvent(event);
250 }
251
252
253 bool Schematic::deserializeFromMts(std::istream *is,
254         std::vector<std::string> *names)
255 {
256         std::istream &ss = *is;
257         content_t cignore = CONTENT_IGNORE;
258         bool have_cignore = false;
259
260         //// Read signature
261         u32 signature = readU32(ss);
262         if (signature != MTSCHEM_FILE_SIGNATURE) {
263                 errorstream << __FUNCTION__ << ": invalid schematic "
264                         "file" << std::endl;
265                 return false;
266         }
267
268         //// Read version
269         u16 version = readU16(ss);
270         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
271                 errorstream << __FUNCTION__ << ": unsupported schematic "
272                         "file version" << std::endl;
273                 return false;
274         }
275
276         //// Read size
277         size = readV3S16(ss);
278
279         //// Read Y-slice probability values
280         delete []slice_probs;
281         slice_probs = new u8[size.Y];
282         for (int y = 0; y != size.Y; y++)
283                 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD;
284
285         //// Read node names
286         u16 nidmapcount = readU16(ss);
287         for (int i = 0; i != nidmapcount; i++) {
288                 std::string name = deSerializeString(ss);
289
290                 // Instances of "ignore" from v1 are converted to air (and instances
291                 // are fixed to have MTSCHEM_PROB_NEVER later on).
292                 if (name == "ignore") {
293                         name = "air";
294                         cignore = i;
295                         have_cignore = true;
296                 }
297
298                 names->push_back(name);
299         }
300
301         //// Read node data
302         size_t nodecount = size.X * size.Y * size.Z;
303
304         delete []schemdata;
305         schemdata = new MapNode[nodecount];
306
307         MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata,
308                 nodecount, 2, 2, true);
309
310         // Fix probability values for nodes that were ignore; removed in v2
311         if (version < 2) {
312                 for (size_t i = 0; i != nodecount; i++) {
313                         if (schemdata[i].param1 == 0)
314                                 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD;
315                         if (have_cignore && schemdata[i].getContent() == cignore)
316                                 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
317                 }
318         }
319
320         // Fix probability values for probability range truncation introduced in v4
321         if (version < 4) {
322                 for (s16 y = 0; y != size.Y; y++)
323                         slice_probs[y] >>= 1;
324                 for (size_t i = 0; i != nodecount; i++)
325                         schemdata[i].param1 >>= 1;
326         }
327
328         return true;
329 }
330
331
332 bool Schematic::serializeToMts(std::ostream *os,
333         const std::vector<std::string> &names)
334 {
335         std::ostream &ss = *os;
336
337         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
338         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
339         writeV3S16(ss, size);                         // schematic size
340
341         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
342                 writeU8(ss, slice_probs[y]);
343
344         writeU16(ss, names.size()); // name count
345         for (size_t i = 0; i != names.size(); i++)
346                 ss << serializeString(names[i]); // node names
347
348         // compressed bulk node data
349         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE,
350                 schemdata, size.X * size.Y * size.Z, 2, 2, true);
351
352         return true;
353 }
354
355
356 bool Schematic::serializeToLua(std::ostream *os,
357         const std::vector<std::string> &names, bool use_comments, u32 indent_spaces)
358 {
359         std::ostream &ss = *os;
360
361         std::string indent("\t");
362         if (indent_spaces > 0)
363                 indent.assign(indent_spaces, ' ');
364
365         //// Write header
366         {
367                 ss << "schematic = {" << std::endl;
368                 ss << indent << "size = "
369                         << "{x=" << size.X
370                         << ", y=" << size.Y
371                         << ", z=" << size.Z
372                         << "}," << std::endl;
373         }
374
375         //// Write y-slice probabilities
376         {
377                 ss << indent << "yslice_prob = {" << std::endl;
378
379                 for (u16 y = 0; y != size.Y; y++) {
380                         u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK;
381
382                         ss << indent << indent << "{"
383                                 << "ypos=" << y
384                                 << ", prob=" << (u16)probability * 2
385                                 << "}," << std::endl;
386                 }
387
388                 ss << indent << "}," << std::endl;
389         }
390
391         //// Write node data
392         {
393                 ss << indent << "data = {" << std::endl;
394
395                 u32 i = 0;
396                 for (u16 z = 0; z != size.Z; z++)
397                 for (u16 y = 0; y != size.Y; y++) {
398                         if (use_comments) {
399                                 ss << std::endl
400                                         << indent << indent
401                                         << "-- z=" << z
402                                         << ", y=" << y << std::endl;
403                         }
404
405                         for (u16 x = 0; x != size.X; x++, i++) {
406                                 u8 probability   = schemdata[i].param1 & MTSCHEM_PROB_MASK;
407                                 bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
408
409                                 ss << indent << indent << "{"
410                                         << "name=\"" << names[schemdata[i].getContent()]
411                                         << "\", prob=" << (u16)probability * 2
412                                         << ", param2=" << (u16)schemdata[i].param2;
413
414                                 if (force_place)
415                                         ss << ", force_place=true";
416
417                                 ss << "}," << std::endl;
418                         }
419                 }
420
421                 ss << indent << "}," << std::endl;
422         }
423
424         ss << "}" << std::endl;
425
426         return true;
427 }
428
429
430 bool Schematic::loadSchematicFromFile(const std::string &filename,
431         const NodeDefManager *ndef, StringMap *replace_names)
432 {
433         std::ifstream is(filename.c_str(), std::ios_base::binary);
434         if (!is.good()) {
435                 errorstream << __FUNCTION__ << ": unable to open file '"
436                         << filename << "'" << std::endl;
437                 return false;
438         }
439
440         size_t origsize = m_nodenames.size();
441         if (!deserializeFromMts(&is, &m_nodenames))
442                 return false;
443
444         m_nnlistsizes.push_back(m_nodenames.size() - origsize);
445
446         name = filename;
447
448         if (replace_names) {
449                 for (size_t i = origsize; i < m_nodenames.size(); i++) {
450                         std::string &node_name = m_nodenames[i];
451                         StringMap::iterator it = replace_names->find(node_name);
452                         if (it != replace_names->end())
453                                 node_name = it->second;
454                 }
455         }
456
457         if (ndef)
458                 ndef->pendNodeResolve(this);
459
460         return true;
461 }
462
463
464 bool Schematic::saveSchematicToFile(const std::string &filename,
465         const NodeDefManager *ndef)
466 {
467         MapNode *orig_schemdata = schemdata;
468         std::vector<std::string> ndef_nodenames;
469         std::vector<std::string> *names;
470
471         if (m_resolve_done && ndef == NULL)
472                 ndef = m_ndef;
473
474         if (ndef) {
475                 names = &ndef_nodenames;
476
477                 u32 volume = size.X * size.Y * size.Z;
478                 schemdata = new MapNode[volume];
479                 for (u32 i = 0; i != volume; i++)
480                         schemdata[i] = orig_schemdata[i];
481
482                 generate_nodelist_and_update_ids(schemdata, volume, names, ndef);
483         } else { // otherwise, use the names we have on hand in the list
484                 names = &m_nodenames;
485         }
486
487         std::ostringstream os(std::ios_base::binary);
488         bool status = serializeToMts(&os, *names);
489
490         if (ndef) {
491                 delete []schemdata;
492                 schemdata = orig_schemdata;
493         }
494
495         if (!status)
496                 return false;
497
498         return fs::safeWriteToFile(filename, os.str());
499 }
500
501
502 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
503 {
504         MMVManip *vm = new MMVManip(map);
505
506         v3s16 bp1 = getNodeBlockPos(p1);
507         v3s16 bp2 = getNodeBlockPos(p2);
508         vm->initialEmerge(bp1, bp2);
509
510         size = p2 - p1 + 1;
511
512         slice_probs = new u8[size.Y];
513         for (s16 y = 0; y != size.Y; y++)
514                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
515
516         schemdata = new MapNode[size.X * size.Y * size.Z];
517
518         u32 i = 0;
519         for (s16 z = p1.Z; z <= p2.Z; z++)
520         for (s16 y = p1.Y; y <= p2.Y; y++) {
521                 u32 vi = vm->m_area.index(p1.X, y, z);
522                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
523                         schemdata[i] = vm->m_data[vi];
524                         schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
525                 }
526         }
527
528         delete vm;
529         return true;
530 }
531
532
533 void Schematic::applyProbabilities(v3s16 p0,
534         std::vector<std::pair<v3s16, u8> > *plist,
535         std::vector<std::pair<s16, u8> > *splist)
536 {
537         for (size_t i = 0; i != plist->size(); i++) {
538                 v3s16 p = (*plist)[i].first - p0;
539                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
540                 if (index < size.Z * size.Y * size.X) {
541                         u8 prob = (*plist)[i].second;
542                         schemdata[index].param1 = prob;
543
544                         // trim unnecessary node names from schematic
545                         if (prob == MTSCHEM_PROB_NEVER)
546                                 schemdata[index].setContent(CONTENT_AIR);
547                 }
548         }
549
550         for (size_t i = 0; i != splist->size(); i++) {
551                 s16 y = (*splist)[i].first - p0.Y;
552                 slice_probs[y] = (*splist)[i].second;
553         }
554 }
555
556
557 void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount,
558         std::vector<std::string> *usednodes, const NodeDefManager *ndef)
559 {
560         std::unordered_map<content_t, content_t> nodeidmap;
561         content_t numids = 0;
562
563         for (size_t i = 0; i != nodecount; i++) {
564                 content_t id;
565                 content_t c = nodes[i].getContent();
566
567                 std::unordered_map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
568                 if (it == nodeidmap.end()) {
569                         id = numids;
570                         numids++;
571
572                         usednodes->push_back(ndef->get(c).name);
573                         nodeidmap.insert(std::make_pair(c, id));
574                 } else {
575                         id = it->second;
576                 }
577                 nodes[i].setContent(id);
578         }
579 }