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