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