]> git.lizzy.rs Git - dragonfireclient.git/blob - src/mapgen/mg_schematic.cpp
Allow ObjDefManager instances to be cloned
[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 ObjDef *Schematic::clone() const
81 {
82         FATAL_ERROR("not cloneable");
83 }
84
85
86 void Schematic::resolveNodeNames()
87 {
88         getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
89
90         size_t bufsize = size.X * size.Y * size.Z;
91         for (size_t i = 0; i != bufsize; i++) {
92                 content_t c_original = schemdata[i].getContent();
93                 content_t c_new = c_nodes[c_original];
94                 schemdata[i].setContent(c_new);
95         }
96 }
97
98
99 void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place)
100 {
101         assert(schemdata && slice_probs);
102         sanity_check(m_ndef != NULL);
103
104         int xstride = 1;
105         int ystride = size.X;
106         int zstride = size.X * size.Y;
107
108         s16 sx = size.X;
109         s16 sy = size.Y;
110         s16 sz = size.Z;
111
112         int i_start, i_step_x, i_step_z;
113         switch (rot) {
114                 case ROTATE_90:
115                         i_start  = sx - 1;
116                         i_step_x = zstride;
117                         i_step_z = -xstride;
118                         SWAP(s16, sx, sz);
119                         break;
120                 case ROTATE_180:
121                         i_start  = zstride * (sz - 1) + sx - 1;
122                         i_step_x = -xstride;
123                         i_step_z = -zstride;
124                         break;
125                 case ROTATE_270:
126                         i_start  = zstride * (sz - 1);
127                         i_step_x = -zstride;
128                         i_step_z = xstride;
129                         SWAP(s16, sx, sz);
130                         break;
131                 default:
132                         i_start  = 0;
133                         i_step_x = xstride;
134                         i_step_z = zstride;
135         }
136
137         s16 y_map = p.Y;
138         for (s16 y = 0; y != sy; y++) {
139                 if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) &&
140                         (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
141                         continue;
142
143                 for (s16 z = 0; z != sz; z++) {
144                         u32 i = z * i_step_z + y * ystride + i_start;
145                         for (s16 x = 0; x != sx; x++, i += i_step_x) {
146                                 v3s16 pos(p.X + x, y_map, p.Z + z);
147                                 if (!vm->m_area.contains(pos))
148                                         continue;
149
150                                 if (schemdata[i].getContent() == CONTENT_IGNORE)
151                                         continue;
152
153                                 u8 placement_prob     = schemdata[i].param1 & MTSCHEM_PROB_MASK;
154                                 bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
155
156                                 if (placement_prob == MTSCHEM_PROB_NEVER)
157                                         continue;
158
159                                 u32 vi = vm->m_area.index(pos);
160                                 if (!force_place && !force_place_node) {
161                                         content_t c = vm->m_data[vi].getContent();
162                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
163                                                 continue;
164                                 }
165
166                                 if ((placement_prob != MTSCHEM_PROB_ALWAYS) &&
167                                         (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
168                                         continue;
169
170                                 vm->m_data[vi] = schemdata[i];
171                                 vm->m_data[vi].param1 = 0;
172
173                                 if (rot)
174                                         vm->m_data[vi].rotateAlongYAxis(m_ndef, rot);
175                         }
176                 }
177                 y_map++;
178         }
179 }
180
181
182 bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags,
183         Rotation rot, bool force_place)
184 {
185         assert(vm != NULL);
186         assert(schemdata && slice_probs);
187         sanity_check(m_ndef != NULL);
188
189         //// Determine effective rotation and effective schematic dimensions
190         if (rot == ROTATE_RAND)
191                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
192
193         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
194                 v3s16(size.Z, size.Y, size.X) : size;
195
196         //// Adjust placement position if necessary
197         if (flags & DECO_PLACE_CENTER_X)
198                 p.X -= (s.X - 1) / 2;
199         if (flags & DECO_PLACE_CENTER_Y)
200                 p.Y -= (s.Y - 1) / 2;
201         if (flags & DECO_PLACE_CENTER_Z)
202                 p.Z -= (s.Z - 1) / 2;
203
204         blitToVManip(vm, p, rot, force_place);
205
206         return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1)));
207 }
208
209 void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags,
210         Rotation rot, bool force_place)
211 {
212         std::map<v3s16, MapBlock *> lighting_modified_blocks;
213         std::map<v3s16, MapBlock *> modified_blocks;
214         std::map<v3s16, MapBlock *>::iterator it;
215
216         assert(map != NULL);
217         assert(schemdata != NULL);
218         sanity_check(m_ndef != NULL);
219
220         //// Determine effective rotation and effective schematic dimensions
221         if (rot == ROTATE_RAND)
222                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
223
224         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
225                         v3s16(size.Z, size.Y, size.X) : size;
226
227         //// Adjust placement position if necessary
228         if (flags & DECO_PLACE_CENTER_X)
229                 p.X -= (s.X - 1) / 2;
230         if (flags & DECO_PLACE_CENTER_Y)
231                 p.Y -= (s.Y - 1) / 2;
232         if (flags & DECO_PLACE_CENTER_Z)
233                 p.Z -= (s.Z - 1) / 2;
234
235         //// Create VManip for effected area, emerge our area, modify area
236         //// inside VManip, then blit back.
237         v3s16 bp1 = getNodeBlockPos(p);
238         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1, 1, 1));
239
240         MMVManip vm(map);
241         vm.initialEmerge(bp1, bp2);
242
243         blitToVManip(&vm, p, rot, force_place);
244
245         voxalgo::blit_back_with_light(map, &vm, &modified_blocks);
246
247         //// Carry out post-map-modification actions
248
249         //// Create & dispatch map modification events to observers
250         MapEditEvent event;
251         event.type = MEET_OTHER;
252         for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it)
253                 event.modified_blocks.insert(it->first);
254
255         map->dispatchEvent(event);
256 }
257
258
259 bool Schematic::deserializeFromMts(std::istream *is,
260         std::vector<std::string> *names)
261 {
262         std::istream &ss = *is;
263         content_t cignore = CONTENT_IGNORE;
264         bool have_cignore = false;
265
266         //// Read signature
267         u32 signature = readU32(ss);
268         if (signature != MTSCHEM_FILE_SIGNATURE) {
269                 errorstream << __FUNCTION__ << ": invalid schematic "
270                         "file" << std::endl;
271                 return false;
272         }
273
274         //// Read version
275         u16 version = readU16(ss);
276         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
277                 errorstream << __FUNCTION__ << ": unsupported schematic "
278                         "file version" << std::endl;
279                 return false;
280         }
281
282         //// Read size
283         size = readV3S16(ss);
284
285         //// Read Y-slice probability values
286         delete []slice_probs;
287         slice_probs = new u8[size.Y];
288         for (int y = 0; y != size.Y; y++)
289                 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD;
290
291         //// Read node names
292         u16 nidmapcount = readU16(ss);
293         for (int i = 0; i != nidmapcount; i++) {
294                 std::string name = deSerializeString(ss);
295
296                 // Instances of "ignore" from v1 are converted to air (and instances
297                 // are fixed to have MTSCHEM_PROB_NEVER later on).
298                 if (name == "ignore") {
299                         name = "air";
300                         cignore = i;
301                         have_cignore = true;
302                 }
303
304                 names->push_back(name);
305         }
306
307         //// Read node data
308         size_t nodecount = size.X * size.Y * size.Z;
309
310         delete []schemdata;
311         schemdata = new MapNode[nodecount];
312
313         MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata,
314                 nodecount, 2, 2, true);
315
316         // Fix probability values for nodes that were ignore; removed in v2
317         if (version < 2) {
318                 for (size_t i = 0; i != nodecount; i++) {
319                         if (schemdata[i].param1 == 0)
320                                 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD;
321                         if (have_cignore && schemdata[i].getContent() == cignore)
322                                 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
323                 }
324         }
325
326         // Fix probability values for probability range truncation introduced in v4
327         if (version < 4) {
328                 for (s16 y = 0; y != size.Y; y++)
329                         slice_probs[y] >>= 1;
330                 for (size_t i = 0; i != nodecount; i++)
331                         schemdata[i].param1 >>= 1;
332         }
333
334         return true;
335 }
336
337
338 bool Schematic::serializeToMts(std::ostream *os,
339         const std::vector<std::string> &names)
340 {
341         std::ostream &ss = *os;
342
343         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
344         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
345         writeV3S16(ss, size);                         // schematic size
346
347         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
348                 writeU8(ss, slice_probs[y]);
349
350         writeU16(ss, names.size()); // name count
351         for (size_t i = 0; i != names.size(); i++)
352                 ss << serializeString(names[i]); // node names
353
354         // compressed bulk node data
355         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE,
356                 schemdata, size.X * size.Y * size.Z, 2, 2, true);
357
358         return true;
359 }
360
361
362 bool Schematic::serializeToLua(std::ostream *os,
363         const std::vector<std::string> &names, bool use_comments, u32 indent_spaces)
364 {
365         std::ostream &ss = *os;
366
367         std::string indent("\t");
368         if (indent_spaces > 0)
369                 indent.assign(indent_spaces, ' ');
370
371         //// Write header
372         {
373                 ss << "schematic = {" << std::endl;
374                 ss << indent << "size = "
375                         << "{x=" << size.X
376                         << ", y=" << size.Y
377                         << ", z=" << size.Z
378                         << "}," << std::endl;
379         }
380
381         //// Write y-slice probabilities
382         {
383                 ss << indent << "yslice_prob = {" << std::endl;
384
385                 for (u16 y = 0; y != size.Y; y++) {
386                         u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK;
387
388                         ss << indent << indent << "{"
389                                 << "ypos=" << y
390                                 << ", prob=" << (u16)probability * 2
391                                 << "}," << std::endl;
392                 }
393
394                 ss << indent << "}," << std::endl;
395         }
396
397         //// Write node data
398         {
399                 ss << indent << "data = {" << std::endl;
400
401                 u32 i = 0;
402                 for (u16 z = 0; z != size.Z; z++)
403                 for (u16 y = 0; y != size.Y; y++) {
404                         if (use_comments) {
405                                 ss << std::endl
406                                         << indent << indent
407                                         << "-- z=" << z
408                                         << ", y=" << y << std::endl;
409                         }
410
411                         for (u16 x = 0; x != size.X; x++, i++) {
412                                 u8 probability   = schemdata[i].param1 & MTSCHEM_PROB_MASK;
413                                 bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
414
415                                 ss << indent << indent << "{"
416                                         << "name=\"" << names[schemdata[i].getContent()]
417                                         << "\", prob=" << (u16)probability * 2
418                                         << ", param2=" << (u16)schemdata[i].param2;
419
420                                 if (force_place)
421                                         ss << ", force_place=true";
422
423                                 ss << "}," << std::endl;
424                         }
425                 }
426
427                 ss << indent << "}," << std::endl;
428         }
429
430         ss << "}" << std::endl;
431
432         return true;
433 }
434
435
436 bool Schematic::loadSchematicFromFile(const std::string &filename,
437         const NodeDefManager *ndef, StringMap *replace_names)
438 {
439         std::ifstream is(filename.c_str(), std::ios_base::binary);
440         if (!is.good()) {
441                 errorstream << __FUNCTION__ << ": unable to open file '"
442                         << filename << "'" << std::endl;
443                 return false;
444         }
445
446         size_t origsize = m_nodenames.size();
447         if (!deserializeFromMts(&is, &m_nodenames))
448                 return false;
449
450         m_nnlistsizes.push_back(m_nodenames.size() - origsize);
451
452         name = filename;
453
454         if (replace_names) {
455                 for (size_t i = origsize; i < m_nodenames.size(); i++) {
456                         std::string &node_name = m_nodenames[i];
457                         StringMap::iterator it = replace_names->find(node_name);
458                         if (it != replace_names->end())
459                                 node_name = it->second;
460                 }
461         }
462
463         if (ndef)
464                 ndef->pendNodeResolve(this);
465
466         return true;
467 }
468
469
470 bool Schematic::saveSchematicToFile(const std::string &filename,
471         const NodeDefManager *ndef)
472 {
473         MapNode *orig_schemdata = schemdata;
474         std::vector<std::string> ndef_nodenames;
475         std::vector<std::string> *names;
476
477         if (m_resolve_done && ndef == NULL)
478                 ndef = m_ndef;
479
480         if (ndef) {
481                 names = &ndef_nodenames;
482
483                 u32 volume = size.X * size.Y * size.Z;
484                 schemdata = new MapNode[volume];
485                 for (u32 i = 0; i != volume; i++)
486                         schemdata[i] = orig_schemdata[i];
487
488                 generate_nodelist_and_update_ids(schemdata, volume, names, ndef);
489         } else { // otherwise, use the names we have on hand in the list
490                 names = &m_nodenames;
491         }
492
493         std::ostringstream os(std::ios_base::binary);
494         bool status = serializeToMts(&os, *names);
495
496         if (ndef) {
497                 delete []schemdata;
498                 schemdata = orig_schemdata;
499         }
500
501         if (!status)
502                 return false;
503
504         return fs::safeWriteToFile(filename, os.str());
505 }
506
507
508 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
509 {
510         MMVManip *vm = new MMVManip(map);
511
512         v3s16 bp1 = getNodeBlockPos(p1);
513         v3s16 bp2 = getNodeBlockPos(p2);
514         vm->initialEmerge(bp1, bp2);
515
516         size = p2 - p1 + 1;
517
518         slice_probs = new u8[size.Y];
519         for (s16 y = 0; y != size.Y; y++)
520                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
521
522         schemdata = new MapNode[size.X * size.Y * size.Z];
523
524         u32 i = 0;
525         for (s16 z = p1.Z; z <= p2.Z; z++)
526         for (s16 y = p1.Y; y <= p2.Y; y++) {
527                 u32 vi = vm->m_area.index(p1.X, y, z);
528                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
529                         schemdata[i] = vm->m_data[vi];
530                         schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
531                 }
532         }
533
534         delete vm;
535         return true;
536 }
537
538
539 void Schematic::applyProbabilities(v3s16 p0,
540         std::vector<std::pair<v3s16, u8> > *plist,
541         std::vector<std::pair<s16, u8> > *splist)
542 {
543         for (size_t i = 0; i != plist->size(); i++) {
544                 v3s16 p = (*plist)[i].first - p0;
545                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
546                 if (index < size.Z * size.Y * size.X) {
547                         u8 prob = (*plist)[i].second;
548                         schemdata[index].param1 = prob;
549
550                         // trim unnecessary node names from schematic
551                         if (prob == MTSCHEM_PROB_NEVER)
552                                 schemdata[index].setContent(CONTENT_AIR);
553                 }
554         }
555
556         for (size_t i = 0; i != splist->size(); i++) {
557                 s16 y = (*splist)[i].first - p0.Y;
558                 slice_probs[y] = (*splist)[i].second;
559         }
560 }
561
562
563 void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount,
564         std::vector<std::string> *usednodes, const NodeDefManager *ndef)
565 {
566         std::unordered_map<content_t, content_t> nodeidmap;
567         content_t numids = 0;
568
569         for (size_t i = 0; i != nodecount; i++) {
570                 content_t id;
571                 content_t c = nodes[i].getContent();
572
573                 std::unordered_map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
574                 if (it == nodeidmap.end()) {
575                         id = numids;
576                         numids++;
577
578                         usednodes->push_back(ndef->get(c).name);
579                         nodeidmap.insert(std::make_pair(c, id));
580                 } else {
581                         id = it->second;
582                 }
583                 nodes[i].setContent(id);
584         }
585 }