NodeResolver: Remove NodeResolveMethod
[oweals/minetest.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 "gamedef.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
34 ///////////////////////////////////////////////////////////////////////////////
35
36
37 SchematicManager::SchematicManager(IGameDef *gamedef) :
38         ObjDefManager(gamedef, OBJDEF_SCHEMATIC)
39 {
40         m_gamedef = gamedef;
41 }
42
43
44 void SchematicManager::clear()
45 {
46         EmergeManager *emerge = m_gamedef->getEmergeManager();
47
48         // Remove all dangling references in Decorations
49         DecorationManager *decomgr = emerge->decomgr;
50         for (size_t i = 0; i != decomgr->getNumObjects(); i++) {
51                 Decoration *deco = (Decoration *)decomgr->getRaw(i);
52
53                 try {
54                         DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco);
55                         if (dschem)
56                                 dschem->schematic = NULL;
57                 } catch (std::bad_cast) {
58                 }
59         }
60
61         ObjDefManager::clear();
62 }
63
64
65 ///////////////////////////////////////////////////////////////////////////////
66
67
68 Schematic::Schematic()
69 {
70         schemdata   = NULL;
71         slice_probs = NULL;
72         flags       = 0;
73         size        = v3s16(0, 0, 0);
74 }
75
76
77 Schematic::~Schematic()
78 {
79         delete []schemdata;
80         delete []slice_probs;
81 }
82
83
84 void Schematic::resolveNodeNames()
85 {
86         getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
87
88         size_t bufsize = size.X * size.Y * size.Z;
89         for (size_t i = 0; i != bufsize; i++) {
90                 content_t c_original = schemdata[i].getContent();
91                 content_t c_new = c_nodes[c_original];
92                 schemdata[i].setContent(c_new);
93         }
94 }
95
96
97 void Schematic::blitToVManip(v3s16 p, MMVManip *vm,
98         Rotation rot, bool force_placement)
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                         myrand_range(1, 255) > slice_probs[y])
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                                 if (schemdata[i].param1 == MTSCHEM_PROB_NEVER)
152                                         continue;
153
154                                 if (!force_placement) {
155                                         content_t c = vm->m_data[vi].getContent();
156                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
157                                                 continue;
158                                 }
159
160                                 if (schemdata[i].param1 != MTSCHEM_PROB_ALWAYS &&
161                                         myrand_range(1, 255) > schemdata[i].param1)
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 void Schematic::placeStructure(Map *map, v3s16 p, u32 flags,
177         Rotation rot, bool force_placement)
178 {
179         assert(schemdata != NULL); // Pre-condition
180         sanity_check(m_ndef != NULL);
181
182         MMVManip *vm = new MMVManip(map);
183
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         if (flags & DECO_PLACE_CENTER_X)
191                 p.X -= (s.X + 1) / 2;
192         if (flags & DECO_PLACE_CENTER_Y)
193                 p.Y -= (s.Y + 1) / 2;
194         if (flags & DECO_PLACE_CENTER_Z)
195                 p.Z -= (s.Z + 1) / 2;
196
197         v3s16 bp1 = getNodeBlockPos(p);
198         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
199         vm->initialEmerge(bp1, bp2);
200
201         blitToVManip(p, vm, rot, force_placement);
202
203         std::map<v3s16, MapBlock *> lighting_modified_blocks;
204         std::map<v3s16, MapBlock *> modified_blocks;
205         vm->blitBackAll(&modified_blocks);
206
207         // TODO: Optimize this by using Mapgen::calcLighting() instead
208         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
209         map->updateLighting(lighting_modified_blocks, modified_blocks);
210
211         MapEditEvent event;
212         event.type = MEET_OTHER;
213         for (std::map<v3s16, MapBlock *>::iterator
214                 it = modified_blocks.begin();
215                 it != modified_blocks.end(); ++it)
216                 event.modified_blocks.insert(it->first);
217
218         map->dispatchEvent(&event);
219 }
220
221
222 bool Schematic::deserializeFromMts(std::istream *is,
223         std::vector<std::string> *names)
224 {
225         std::istream &ss = *is;
226         content_t cignore = CONTENT_IGNORE;
227         bool have_cignore = false;
228
229         u32 signature = readU32(ss);
230         if (signature != MTSCHEM_FILE_SIGNATURE) {
231                 errorstream << "Schematic::deserializeFromMts: invalid schematic "
232                         "file" << std::endl;
233                 return false;
234         }
235
236         u16 version = readU16(ss);
237         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
238                 errorstream << "Schematic::deserializeFromMts: unsupported schematic "
239                         "file version" << std::endl;
240                 return false;
241         }
242
243         size = readV3S16(ss);
244
245         delete []slice_probs;
246         slice_probs = new u8[size.Y];
247         for (int y = 0; y != size.Y; y++)
248                 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS;
249
250         u16 nidmapcount = readU16(ss);
251         for (int i = 0; i != nidmapcount; i++) {
252                 std::string name = deSerializeString(ss);
253
254                 // Instances of "ignore" from ver 1 are converted to air (and instances
255                 // are fixed to have MTSCHEM_PROB_NEVER later on).
256                 if (name == "ignore") {
257                         name = "air";
258                         cignore = i;
259                         have_cignore = true;
260                 }
261
262                 names->push_back(name);
263         }
264
265         size_t nodecount = size.X * size.Y * size.Z;
266
267         delete []schemdata;
268         schemdata = new MapNode[nodecount];
269
270         MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata,
271                 nodecount, 2, 2, true);
272
273         // fix any probability values for nodes that were ignore
274         if (version == 1) {
275                 for (size_t i = 0; i != nodecount; i++) {
276                         if (schemdata[i].param1 == 0)
277                                 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
278                         if (have_cignore && schemdata[i].getContent() == cignore)
279                                 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
280                 }
281         }
282
283         return true;
284 }
285
286
287 bool Schematic::serializeToMts(std::ostream *os,
288         const std::vector<std::string> &names)
289 {
290         std::ostream &ss = *os;
291
292         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
293         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
294         writeV3S16(ss, size);                         // schematic size
295
296         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
297                 writeU8(ss, slice_probs[y]);
298
299         writeU16(ss, names.size()); // name count
300         for (size_t i = 0; i != names.size(); i++)
301                 ss << serializeString(names[i]); // node names
302
303         // compressed bulk node data
304         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE,
305                 schemdata, size.X * size.Y * size.Z, 2, 2, true);
306
307         return true;
308 }
309
310
311 bool Schematic::serializeToLua(std::ostream *os,
312         const std::vector<std::string> &names, bool use_comments)
313 {
314         std::ostream &ss = *os;
315
316         //// Write header
317         {
318                 ss << "schematic = {" << std::endl;
319                 ss << "\tsize = "
320                         << "{x=" << size.X
321                         << ", y=" << size.Y
322                         << ", z=" << size.Z
323                         << "}," << std::endl;
324         }
325
326         //// Write y-slice probabilities
327         {
328                 ss << "\tyslice_prob = {" << std::endl;
329
330                 for (u16 y = 0; y != size.Y; y++) {
331                         ss << "\t\t{"
332                                 << "ypos=" << y
333                                 << ", prob=" << (u16)slice_probs[y]
334                                 << "}," << std::endl;
335                 }
336
337                 ss << "\t}," << std::endl;
338         }
339
340         //// Write node data
341         {
342                 ss << "\tdata = {" << std::endl;
343
344                 u32 i = 0;
345                 for (u16 z = 0; z != size.Z; z++)
346                 for (u16 y = 0; y != size.Y; y++) {
347                         if (use_comments) {
348                                 ss << std::endl
349                                         << "\t\t-- z=" << z
350                                         << ", y=" << y << std::endl;
351                         }
352
353                         for (u16 x = 0; x != size.X; x++, i++) {
354                                 ss << "\t\t{"
355                                         << "name=\"" << names[schemdata[i].getContent()]
356                                         << "\", param1=" << (u16)schemdata[i].param1
357                                         << ", param2=" << (u16)schemdata[i].param2
358                                         << "}," << std::endl;
359                         }
360                 }
361
362                 ss << "\t}," << std::endl;
363         }
364
365         ss << "}" << std::endl;
366
367         return true;
368 }
369
370
371 bool Schematic::loadSchematicFromFile(const std::string &filename,
372         INodeDefManager *ndef, StringMap *replace_names)
373 {
374         std::ifstream is(filename.c_str(), std::ios_base::binary);
375         if (!is.good()) {
376                 errorstream << "Schematic::loadSchematicFile: unable to open file '"
377                         << filename << "'" << std::endl;
378                 return false;
379         }
380
381         size_t origsize = m_nodenames.size();
382         if (!deserializeFromMts(&is, &m_nodenames))
383                 return false;
384
385         if (replace_names) {
386                 for (size_t i = origsize; i != m_nodenames.size(); i++) {
387                         std::string &name = m_nodenames[i];
388                         StringMap::iterator it = replace_names->find(name);
389                         if (it != replace_names->end())
390                                 name = it->second;
391                 }
392         }
393
394         m_nnlistsizes.push_back(m_nodenames.size() - origsize);
395
396         if (ndef)
397                 ndef->pendNodeResolve(this);
398
399         return true;
400 }
401
402
403 bool Schematic::saveSchematicToFile(const std::string &filename)
404 {
405         MapNode *orig_schemdata = schemdata;
406         std::vector<std::string> ndef_nodenames;
407         std::vector<std::string> *names;
408
409         // Only carry out the modification if we know the nodes
410         // were resolved at this point
411         if (m_resolve_done) {
412                 names = &ndef_nodenames;
413
414                 u32 volume = size.X * size.Y * size.Z;
415                 schemdata = new MapNode[volume];
416                 for (u32 i = 0; i != volume; i++)
417                         schemdata[i] = orig_schemdata[i];
418
419                 generate_nodelist_and_update_ids(schemdata, volume, names, m_ndef);
420         } else { // otherwise, use the names we have on hand in the list
421                 names = &m_nodenames;
422         }
423
424         std::ostringstream os(std::ios_base::binary);
425         serializeToMts(&os, *names);
426
427         if (m_resolve_done) {
428                 delete []schemdata;
429                 schemdata = orig_schemdata;
430         }
431
432         return fs::safeWriteToFile(filename, os.str());
433 }
434
435
436 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
437 {
438         MMVManip *vm = new MMVManip(map);
439
440         v3s16 bp1 = getNodeBlockPos(p1);
441         v3s16 bp2 = getNodeBlockPos(p2);
442         vm->initialEmerge(bp1, bp2);
443
444         size = p2 - p1 + 1;
445
446         slice_probs = new u8[size.Y];
447         for (s16 y = 0; y != size.Y; y++)
448                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
449
450         schemdata = new MapNode[size.X * size.Y * size.Z];
451
452         u32 i = 0;
453         for (s16 z = p1.Z; z <= p2.Z; z++)
454         for (s16 y = p1.Y; y <= p2.Y; y++) {
455                 u32 vi = vm->m_area.index(p1.X, y, z);
456                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
457                         schemdata[i] = vm->m_data[vi];
458                         schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
459                 }
460         }
461
462         delete vm;
463         return true;
464 }
465
466
467 void Schematic::applyProbabilities(v3s16 p0,
468         std::vector<std::pair<v3s16, u8> > *plist,
469         std::vector<std::pair<s16, u8> > *splist)
470 {
471         for (size_t i = 0; i != plist->size(); i++) {
472                 v3s16 p = (*plist)[i].first - p0;
473                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
474                 if (index < size.Z * size.Y * size.X) {
475                         u8 prob = (*plist)[i].second;
476                         schemdata[index].param1 = prob;
477
478                         // trim unnecessary node names from schematic
479                         if (prob == MTSCHEM_PROB_NEVER)
480                                 schemdata[index].setContent(CONTENT_AIR);
481                 }
482         }
483
484         for (size_t i = 0; i != splist->size(); i++) {
485                 s16 y = (*splist)[i].first - p0.Y;
486                 slice_probs[y] = (*splist)[i].second;
487         }
488 }
489
490
491 void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount,
492         std::vector<std::string> *usednodes, INodeDefManager *ndef)
493 {
494         std::map<content_t, content_t> nodeidmap;
495         content_t numids = 0;
496
497         for (size_t i = 0; i != nodecount; i++) {
498                 content_t id;
499                 content_t c = nodes[i].getContent();
500
501                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
502                 if (it == nodeidmap.end()) {
503                         id = numids;
504                         numids++;
505
506                         usednodes->push_back(ndef->get(c).name);
507                         nodeidmap.insert(std::make_pair(c, id));
508                 } else {
509                         id = it->second;
510                 }
511                 nodes[i].setContent(id);
512         }
513 }