]> git.lizzy.rs Git - dragonfireclient.git/blob - src/mg_schematic.cpp
Schematics: Refactor NodeResolver and add NodeResolveMethod
[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 "mg_schematic.h"
22 #include "mapgen.h"
23 #include "map.h"
24 #include "mapblock.h"
25 #include "log.h"
26 #include "util/numeric.h"
27 #include "util/serialize.h"
28 #include "serialization.h"
29 #include "filesys.h"
30
31 ///////////////////////////////////////////////////////////////////////////////
32
33
34 SchematicManager::SchematicManager(IGameDef *gamedef) :
35         ObjDefManager(gamedef, OBJDEF_SCHEMATIC)
36 {
37 }
38
39
40 ///////////////////////////////////////////////////////////////////////////////
41
42
43 Schematic::Schematic()
44 {
45         schemdata   = NULL;
46         slice_probs = NULL;
47         flags       = 0;
48         size        = v3s16(0, 0, 0);
49 }
50
51
52 Schematic::~Schematic()
53 {
54         delete []schemdata;
55         delete []slice_probs;
56 }
57
58
59 void Schematic::resolveNodeNames()
60 {
61         getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
62
63         size_t bufsize = size.X * size.Y * size.Z;
64         for (size_t i = 0; i != bufsize; i++) {
65                 content_t c_original = schemdata[i].getContent();
66                 content_t c_new = c_nodes[c_original];
67                 schemdata[i].setContent(c_new);
68         }
69 }
70
71
72 void Schematic::blitToVManip(v3s16 p, MMVManip *vm, Rotation rot,
73         bool force_placement, INodeDefManager *ndef)
74 {
75         int xstride = 1;
76         int ystride = size.X;
77         int zstride = size.X * size.Y;
78
79         s16 sx = size.X;
80         s16 sy = size.Y;
81         s16 sz = size.Z;
82
83         int i_start, i_step_x, i_step_z;
84         switch (rot) {
85                 case ROTATE_90:
86                         i_start  = sx - 1;
87                         i_step_x = zstride;
88                         i_step_z = -xstride;
89                         SWAP(s16, sx, sz);
90                         break;
91                 case ROTATE_180:
92                         i_start  = zstride * (sz - 1) + sx - 1;
93                         i_step_x = -xstride;
94                         i_step_z = -zstride;
95                         break;
96                 case ROTATE_270:
97                         i_start  = zstride * (sz - 1);
98                         i_step_x = -zstride;
99                         i_step_z = xstride;
100                         SWAP(s16, sx, sz);
101                         break;
102                 default:
103                         i_start  = 0;
104                         i_step_x = xstride;
105                         i_step_z = zstride;
106         }
107
108         s16 y_map = p.Y;
109         for (s16 y = 0; y != sy; y++) {
110                 if (slice_probs[y] != MTSCHEM_PROB_ALWAYS &&
111                         myrand_range(1, 255) > slice_probs[y])
112                         continue;
113
114                 for (s16 z = 0; z != sz; z++) {
115                         u32 i = z * i_step_z + y * ystride + i_start;
116                         for (s16 x = 0; x != sx; x++, i += i_step_x) {
117                                 u32 vi = vm->m_area.index(p.X + x, y_map, p.Z + z);
118                                 if (!vm->m_area.contains(vi))
119                                         continue;
120
121                                 if (schemdata[i].getContent() == CONTENT_IGNORE)
122                                         continue;
123
124                                 if (schemdata[i].param1 == MTSCHEM_PROB_NEVER)
125                                         continue;
126
127                                 if (!force_placement) {
128                                         content_t c = vm->m_data[vi].getContent();
129                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
130                                                 continue;
131                                 }
132
133                                 if (schemdata[i].param1 != MTSCHEM_PROB_ALWAYS &&
134                                         myrand_range(1, 255) > schemdata[i].param1)
135                                         continue;
136
137                                 vm->m_data[vi] = schemdata[i];
138                                 vm->m_data[vi].param1 = 0;
139
140                                 if (rot)
141                                         vm->m_data[vi].rotateAlongYAxis(ndef, rot);
142                         }
143                 }
144                 y_map++;
145         }
146 }
147
148
149 void Schematic::placeStructure(Map *map, v3s16 p, u32 flags, Rotation rot,
150         bool force_placement, INodeDefManager *ndef)
151 {
152         assert(schemdata != NULL); // Pre-condition
153         MMVManip *vm = new MMVManip(map);
154
155         if (rot == ROTATE_RAND)
156                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
157
158         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
159                                 v3s16(size.Z, size.Y, size.X) : size;
160
161         if (flags & DECO_PLACE_CENTER_X)
162                 p.X -= (s.X + 1) / 2;
163         if (flags & DECO_PLACE_CENTER_Y)
164                 p.Y -= (s.Y + 1) / 2;
165         if (flags & DECO_PLACE_CENTER_Z)
166                 p.Z -= (s.Z + 1) / 2;
167
168         v3s16 bp1 = getNodeBlockPos(p);
169         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
170         vm->initialEmerge(bp1, bp2);
171
172         blitToVManip(p, vm, rot, force_placement, ndef);
173
174         std::map<v3s16, MapBlock *> lighting_modified_blocks;
175         std::map<v3s16, MapBlock *> modified_blocks;
176         vm->blitBackAll(&modified_blocks);
177
178         // TODO: Optimize this by using Mapgen::calcLighting() instead
179         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
180         map->updateLighting(lighting_modified_blocks, modified_blocks);
181
182         MapEditEvent event;
183         event.type = MEET_OTHER;
184         for (std::map<v3s16, MapBlock *>::iterator
185                 it = modified_blocks.begin();
186                 it != modified_blocks.end(); ++it)
187                 event.modified_blocks.insert(it->first);
188
189         map->dispatchEvent(&event);
190 }
191
192
193 bool Schematic::deserializeFromMts(std::istream *is, std::vector<std::string> *names)
194 {
195         std::istream &ss = *is;
196         content_t cignore = CONTENT_IGNORE;
197         bool have_cignore = false;
198
199         u32 signature = readU32(ss);
200         if (signature != MTSCHEM_FILE_SIGNATURE) {
201                 errorstream << "Schematic::deserializeFromMts: invalid schematic "
202                         "file" << std::endl;
203                 return false;
204         }
205
206         u16 version = readU16(ss);
207         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
208                 errorstream << "Schematic::deserializeFromMts: unsupported schematic "
209                         "file version" << std::endl;
210                 return false;
211         }
212
213         size = readV3S16(ss);
214
215         delete []slice_probs;
216         slice_probs = new u8[size.Y];
217         for (int y = 0; y != size.Y; y++)
218                 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS;
219
220         u16 nidmapcount = readU16(ss);
221         for (int i = 0; i != nidmapcount; i++) {
222                 std::string name = deSerializeString(ss);
223
224                 // Instances of "ignore" from ver 1 are converted to air (and instances
225                 // are fixed to have MTSCHEM_PROB_NEVER later on).
226                 if (name == "ignore") {
227                         name = "air";
228                         cignore = i;
229                         have_cignore = true;
230                 }
231
232                 names->push_back(name);
233         }
234
235         size_t nodecount = size.X * size.Y * size.Z;
236
237         delete []schemdata;
238         schemdata = new MapNode[nodecount];
239
240         MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata,
241                 nodecount, 2, 2, true);
242
243         // fix any probability values for nodes that were ignore
244         if (version == 1) {
245                 for (size_t i = 0; i != nodecount; i++) {
246                         if (schemdata[i].param1 == 0)
247                                 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
248                         if (have_cignore && schemdata[i].getContent() == cignore)
249                                 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
250                 }
251         }
252
253         return true;
254 }
255
256
257 bool Schematic::serializeToMts(std::ostream *os)
258 {
259         std::ostream &ss = *os;
260
261         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
262         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
263         writeV3S16(ss, size);                         // schematic size
264
265         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
266                 writeU8(ss, slice_probs[y]);
267
268         std::vector<content_t> usednodes;
269         int nodecount = size.X * size.Y * size.Z;
270         build_nnlist_and_update_ids(schemdata, nodecount, &usednodes);
271
272         u16 numids = usednodes.size();
273         writeU16(ss, numids); // name count
274         for (int i = 0; i != numids; i++)
275                 ss << serializeString(getNodeName(usednodes[i])); // node names
276
277         // compressed bulk node data
278         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE,
279                 schemdata, nodecount, 2, 2, true);
280
281         return true;
282 }
283
284
285 bool Schematic::serializeToLua(std::ostream *os, bool use_comments)
286 {
287         std::ostream &ss = *os;
288
289         //// Write header
290         {
291                 ss << "schematic = {" << std::endl;
292                 ss << "\tsize = "
293                         << "{x=" << size.X
294                         << ", y=" << size.Y
295                         << ", z=" << size.Z
296                         << "}," << std::endl;
297         }
298
299         //// Write y-slice probabilities
300         {
301                 ss << "\tyslice_prob = {" << std::endl;
302
303                 for (u16 y = 0; y != size.Y; y++) {
304                         ss << "\t\t{"
305                                 << "ypos=" << y
306                                 << ", prob=" << (u16)slice_probs[y]
307                                 << "}," << std::endl;
308                 }
309
310                 ss << "\t}," << std::endl;
311         }
312
313         //// Write node data
314         {
315                 ss << "\tdata = {" << std::endl;
316
317                 u32 i = 0;
318                 for (u16 z = 0; z != size.Z; z++)
319                 for (u16 y = 0; y != size.Y; y++) {
320                         if (use_comments) {
321                                 ss << std::endl
322                                         << "\t\t-- z=" << z
323                                         << ", y=" << y << std::endl;
324                         }
325
326                         for (u16 x = 0; x != size.X; x++, i++) {
327                                 ss << "\t\t{"
328                                         << "name=\"" << getNodeName(schemdata[i].getContent())
329                                         << "\", param1=" << (u16)schemdata[i].param1
330                                         << ", param2=" << (u16)schemdata[i].param2
331                                         << "}," << std::endl;
332                         }
333                 }
334
335                 ss << "\t}," << std::endl;
336         }
337
338         ss << "}" << std::endl;
339
340         return true;
341 }
342
343
344 bool Schematic::loadSchematicFromFile(const std::string &filename,
345         INodeDefManager *ndef, StringMap *replace_names,
346         NodeResolveMethod resolve_method)
347 {
348         std::ifstream is(filename, std::ios_base::binary);
349         if (!is.good()) {
350                 errorstream << "Schematic::loadSchematicFile: unable to open file '"
351                         << filename << "'" << std::endl;
352                 return false;
353         }
354
355         size_t origsize = m_nodenames.size();
356         if (!deserializeFromMts(&is, &m_nodenames))
357                 return false;
358
359         if (replace_names) {
360                 for (size_t i = origsize; i != m_nodenames.size(); i++) {
361                         std::string &name = m_nodenames[i];
362                         StringMap::iterator it = replace_names->find(name);
363                         if (it != replace_names->end())
364                                 name = it->second;
365                 }
366         }
367
368         m_nnlistsizes.push_back(m_nodenames.size() - origsize);
369
370         ndef->pendNodeResolve(this, resolve_method);
371
372         return true;
373 }
374
375
376 bool Schematic::saveSchematicToFile(const std::string &filename)
377 {
378         std::ostringstream os(std::ios_base::binary);
379         serializeToMts(&os);
380         return fs::safeWriteToFile(filename, os.str());
381 }
382
383
384 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
385 {
386         MMVManip *vm = new MMVManip(map);
387
388         v3s16 bp1 = getNodeBlockPos(p1);
389         v3s16 bp2 = getNodeBlockPos(p2);
390         vm->initialEmerge(bp1, bp2);
391
392         size = p2 - p1 + 1;
393
394         slice_probs = new u8[size.Y];
395         for (s16 y = 0; y != size.Y; y++)
396                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
397
398         schemdata = new MapNode[size.X * size.Y * size.Z];
399
400         u32 i = 0;
401         for (s16 z = p1.Z; z <= p2.Z; z++)
402         for (s16 y = p1.Y; y <= p2.Y; y++) {
403                 u32 vi = vm->m_area.index(p1.X, y, z);
404                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
405                         schemdata[i] = vm->m_data[vi];
406                         schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
407                 }
408         }
409
410         delete vm;
411         return true;
412 }
413
414
415 void Schematic::applyProbabilities(v3s16 p0,
416         std::vector<std::pair<v3s16, u8> > *plist,
417         std::vector<std::pair<s16, u8> > *splist)
418 {
419         for (size_t i = 0; i != plist->size(); i++) {
420                 v3s16 p = (*plist)[i].first - p0;
421                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
422                 if (index < size.Z * size.Y * size.X) {
423                         u8 prob = (*plist)[i].second;
424                         schemdata[index].param1 = prob;
425
426                         // trim unnecessary node names from schematic
427                         if (prob == MTSCHEM_PROB_NEVER)
428                                 schemdata[index].setContent(CONTENT_AIR);
429                 }
430         }
431
432         for (size_t i = 0; i != splist->size(); i++) {
433                 s16 y = (*splist)[i].first - p0.Y;
434                 slice_probs[y] = (*splist)[i].second;
435         }
436 }
437
438
439 void build_nnlist_and_update_ids(MapNode *nodes, u32 nodecount,
440         std::vector<content_t> *usednodes)
441 {
442         std::map<content_t, content_t> nodeidmap;
443         content_t numids = 0;
444
445         for (u32 i = 0; i != nodecount; i++) {
446                 content_t id;
447                 content_t c = nodes[i].getContent();
448
449                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
450                 if (it == nodeidmap.end()) {
451                         id = numids;
452                         numids++;
453
454                         usednodes->push_back(c);
455                         nodeidmap.insert(std::make_pair(c, id));
456                 } else {
457                         id = it->second;
458                 }
459                 nodes[i].setContent(id);
460         }
461 }