3 Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
4 Copyright (C) 2015-2018 paramat
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.
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.
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.
23 #include "mg_schematic.h"
30 #include "util/numeric.h"
31 #include "util/serialize.h"
32 #include "serialization.h"
34 #include "voxelalgorithms.h"
36 ///////////////////////////////////////////////////////////////////////////////
38 SchematicManager::SchematicManager(Server *server) :
39 ObjDefManager(server, OBJDEF_SCHEMATIC), m_server(server)
43 SchematicManager *SchematicManager::clone() const
45 auto mgr = new SchematicManager();
47 ObjDefManager::cloneTo(mgr);
51 void SchematicManager::clear()
53 EmergeManager *emerge = m_server->getEmergeManager();
55 // Remove all dangling references in Decorations
56 DecorationManager *decomgr = emerge->getWritableDecorationManager();
57 for (size_t i = 0; i != decomgr->getNumObjects(); i++) {
58 Decoration *deco = (Decoration *)decomgr->getRaw(i);
61 DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco);
63 dschem->schematic = NULL;
64 } catch (const std::bad_cast &) {
68 ObjDefManager::clear();
71 ///////////////////////////////////////////////////////////////////////////////
73 Schematic::Schematic() = default;
75 Schematic::~Schematic()
81 ObjDef *Schematic::clone() const
83 auto def = new Schematic();
85 NodeResolver::cloneTo(def);
87 def->c_nodes = c_nodes;
90 FATAL_ERROR_IF(!schemdata, "Schematic can only be cloned after loading");
91 u32 nodecount = size.X * size.Y * size.Z;
92 def->schemdata = new MapNode[nodecount];
93 memcpy(def->schemdata, schemdata, sizeof(MapNode) * nodecount);
94 def->slice_probs = new u8[size.Y];
95 memcpy(def->slice_probs, slice_probs, sizeof(u8) * size.Y);
100 void Schematic::resolveNodeNames()
102 getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
104 size_t bufsize = size.X * size.Y * size.Z;
105 for (size_t i = 0; i != bufsize; i++) {
106 content_t c_original = schemdata[i].getContent();
107 content_t c_new = c_nodes[c_original];
108 schemdata[i].setContent(c_new);
112 void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place)
114 assert(schemdata && slice_probs);
115 sanity_check(m_ndef != NULL);
118 int ystride = size.X;
119 int zstride = size.X * size.Y;
125 int i_start, i_step_x, i_step_z;
134 i_start = zstride * (sz - 1) + sx - 1;
139 i_start = zstride * (sz - 1);
151 for (s16 y = 0; y != sy; y++) {
152 if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) &&
153 (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
156 for (s16 z = 0; z != sz; z++) {
157 u32 i = z * i_step_z + y * ystride + i_start;
158 for (s16 x = 0; x != sx; x++, i += i_step_x) {
159 v3s16 pos(p.X + x, y_map, p.Z + z);
160 if (!vm->m_area.contains(pos))
163 if (schemdata[i].getContent() == CONTENT_IGNORE)
167 schemdata[i].param1 & MTSCHEM_PROB_MASK;
168 bool force_place_node =
169 schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
171 if (placement_prob == MTSCHEM_PROB_NEVER)
174 u32 vi = vm->m_area.index(pos);
175 if (!force_place && !force_place_node) {
176 content_t c = vm->m_data[vi].getContent();
177 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
181 if ((placement_prob != MTSCHEM_PROB_ALWAYS) &&
183 myrand_range(1, MTSCHEM_PROB_ALWAYS)))
186 vm->m_data[vi] = schemdata[i];
187 vm->m_data[vi].param1 = 0;
190 vm->m_data[vi].rotateAlongYAxis(m_ndef, rot);
197 bool Schematic::placeOnVManip(
198 MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place)
201 assert(schemdata && slice_probs);
202 sanity_check(m_ndef != NULL);
204 //// Determine effective rotation and effective schematic dimensions
205 if (rot == ROTATE_RAND)
206 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
208 v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X)
211 //// Adjust placement position if necessary
212 if (flags & DECO_PLACE_CENTER_X)
213 p.X -= (s.X - 1) / 2;
214 if (flags & DECO_PLACE_CENTER_Y)
215 p.Y -= (s.Y - 1) / 2;
216 if (flags & DECO_PLACE_CENTER_Z)
217 p.Z -= (s.Z - 1) / 2;
219 blitToVManip(vm, p, rot, force_place);
221 return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1)));
224 void Schematic::placeOnMap(
225 ServerMap *map, v3s16 p, u32 flags, Rotation rot, bool force_place)
227 std::map<v3s16, MapBlock *> lighting_modified_blocks;
228 std::map<v3s16, MapBlock *> modified_blocks;
229 std::map<v3s16, MapBlock *>::iterator it;
232 assert(schemdata != NULL);
233 sanity_check(m_ndef != NULL);
235 //// Determine effective rotation and effective schematic dimensions
236 if (rot == ROTATE_RAND)
237 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
239 v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X)
242 //// Adjust placement position if necessary
243 if (flags & DECO_PLACE_CENTER_X)
244 p.X -= (s.X - 1) / 2;
245 if (flags & DECO_PLACE_CENTER_Y)
246 p.Y -= (s.Y - 1) / 2;
247 if (flags & DECO_PLACE_CENTER_Z)
248 p.Z -= (s.Z - 1) / 2;
250 //// Create VManip for effected area, emerge our area, modify area
251 //// inside VManip, then blit back.
252 v3s16 bp1 = getNodeBlockPos(p);
253 v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1, 1, 1));
256 vm.initialEmerge(bp1, bp2);
258 blitToVManip(&vm, p, rot, force_place);
260 voxalgo::blit_back_with_light(map, &vm, &modified_blocks);
262 //// Carry out post-map-modification actions
264 //// Create & dispatch map modification events to observers
266 event.type = MEET_OTHER;
267 for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it)
268 event.modified_blocks.insert(it->first);
270 map->dispatchEvent(event);
273 bool Schematic::deserializeFromMts(std::istream *is, std::vector<std::string> *names)
275 std::istream &ss = *is;
276 content_t cignore = CONTENT_IGNORE;
277 bool have_cignore = false;
280 u32 signature = readU32(ss);
281 if (signature != MTSCHEM_FILE_SIGNATURE) {
282 errorstream << __FUNCTION__
283 << ": invalid schematic "
290 u16 version = readU16(ss);
291 if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
292 errorstream << __FUNCTION__
293 << ": unsupported schematic "
300 size = readV3S16(ss);
302 //// Read Y-slice probability values
303 delete[] slice_probs;
304 slice_probs = new u8[size.Y];
305 for (int y = 0; y != size.Y; y++)
306 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD;
309 u16 nidmapcount = readU16(ss);
310 for (int i = 0; i != nidmapcount; i++) {
311 std::string name = deSerializeString(ss);
313 // Instances of "ignore" from v1 are converted to air (and instances
314 // are fixed to have MTSCHEM_PROB_NEVER later on).
315 if (name == "ignore") {
321 names->push_back(name);
325 size_t nodecount = size.X * size.Y * size.Z;
328 schemdata = new MapNode[nodecount];
330 MapNode::deSerializeBulk(
331 ss, SER_FMT_VER_HIGHEST_READ, schemdata, nodecount, 2, 2, true);
333 // Fix probability values for nodes that were ignore; removed in v2
335 for (size_t i = 0; i != nodecount; i++) {
336 if (schemdata[i].param1 == 0)
337 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD;
338 if (have_cignore && schemdata[i].getContent() == cignore)
339 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
343 // Fix probability values for probability range truncation introduced in v4
345 for (s16 y = 0; y != size.Y; y++)
346 slice_probs[y] >>= 1;
347 for (size_t i = 0; i != nodecount; i++)
348 schemdata[i].param1 >>= 1;
354 bool Schematic::serializeToMts(
355 std::ostream *os, const std::vector<std::string> &names) const
357 std::ostream &ss = *os;
359 writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature
360 writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
361 writeV3S16(ss, size); // schematic size
363 for (int y = 0; y != size.Y; y++) // Y slice probabilities
364 writeU8(ss, slice_probs[y]);
366 writeU16(ss, names.size()); // name count
367 for (size_t i = 0; i != names.size(); i++)
368 ss << serializeString(names[i]); // node names
370 // compressed bulk node data
371 MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, schemdata,
372 size.X * size.Y * size.Z, 2, 2, true);
377 bool Schematic::serializeToLua(std::ostream *os, const std::vector<std::string> &names,
378 bool use_comments, u32 indent_spaces) const
380 std::ostream &ss = *os;
382 std::string indent("\t");
383 if (indent_spaces > 0)
384 indent.assign(indent_spaces, ' ');
388 ss << "schematic = {" << std::endl;
389 ss << indent << "size = "
390 << "{x=" << size.X << ", y=" << size.Y << ", z=" << size.Z << "},"
394 //// Write y-slice probabilities
396 ss << indent << "yslice_prob = {" << std::endl;
398 for (u16 y = 0; y != size.Y; y++) {
399 u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK;
401 ss << indent << indent << "{"
402 << "ypos=" << y << ", prob=" << (u16)probability * 2 << "},"
406 ss << indent << "}," << std::endl;
411 ss << indent << "data = {" << std::endl;
414 for (u16 z = 0; z != size.Z; z++)
415 for (u16 y = 0; y != size.Y; y++) {
418 << indent << indent << "-- z=" << z
419 << ", y=" << y << std::endl;
422 for (u16 x = 0; x != size.X; x++, i++) {
423 u8 probability = schemdata[i].param1 &
425 bool force_place = schemdata[i].param1 &
428 ss << indent << indent << "{"
430 << names[schemdata[i].getContent()]
431 << "\", prob=" << (u16)probability * 2
432 << ", param2=" << (u16)schemdata[i].param2;
435 ss << ", force_place=true";
437 ss << "}," << std::endl;
441 ss << indent << "}," << std::endl;
444 ss << "}" << std::endl;
449 bool Schematic::loadSchematicFromFile(const std::string &filename,
450 const NodeDefManager *ndef, StringMap *replace_names)
452 std::ifstream is(filename.c_str(), std::ios_base::binary);
454 errorstream << __FUNCTION__ << ": unable to open file '" << filename
459 size_t origsize = m_nodenames.size();
460 if (!deserializeFromMts(&is, &m_nodenames))
463 m_nnlistsizes.push_back(m_nodenames.size() - origsize);
468 for (size_t i = origsize; i < m_nodenames.size(); i++) {
469 std::string &node_name = m_nodenames[i];
470 StringMap::iterator it = replace_names->find(node_name);
471 if (it != replace_names->end())
472 node_name = it->second;
477 ndef->pendNodeResolve(this);
482 bool Schematic::saveSchematicToFile(
483 const std::string &filename, const NodeDefManager *ndef)
485 MapNode *orig_schemdata = schemdata;
486 std::vector<std::string> ndef_nodenames;
487 std::vector<std::string> *names;
489 if (m_resolve_done && ndef == NULL)
493 names = &ndef_nodenames;
495 u32 volume = size.X * size.Y * size.Z;
496 schemdata = new MapNode[volume];
497 for (u32 i = 0; i != volume; i++)
498 schemdata[i] = orig_schemdata[i];
500 generate_nodelist_and_update_ids(schemdata, volume, names, ndef);
501 } else { // otherwise, use the names we have on hand in the list
502 names = &m_nodenames;
505 std::ostringstream os(std::ios_base::binary);
506 bool status = serializeToMts(&os, *names);
510 schemdata = orig_schemdata;
516 return fs::safeWriteToFile(filename, os.str());
519 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
521 MMVManip *vm = new MMVManip(map);
523 v3s16 bp1 = getNodeBlockPos(p1);
524 v3s16 bp2 = getNodeBlockPos(p2);
525 vm->initialEmerge(bp1, bp2);
529 slice_probs = new u8[size.Y];
530 for (s16 y = 0; y != size.Y; y++)
531 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
533 schemdata = new MapNode[size.X * size.Y * size.Z];
536 for (s16 z = p1.Z; z <= p2.Z; z++)
537 for (s16 y = p1.Y; y <= p2.Y; y++) {
538 u32 vi = vm->m_area.index(p1.X, y, z);
539 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
540 schemdata[i] = vm->m_data[vi];
541 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
549 void Schematic::applyProbabilities(v3s16 p0, std::vector<std::pair<v3s16, u8>> *plist,
550 std::vector<std::pair<s16, u8>> *splist)
552 for (size_t i = 0; i != plist->size(); i++) {
553 v3s16 p = (*plist)[i].first - p0;
554 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
555 if (index < size.Z * size.Y * size.X) {
556 u8 prob = (*plist)[i].second;
557 schemdata[index].param1 = prob;
559 // trim unnecessary node names from schematic
560 if (prob == MTSCHEM_PROB_NEVER)
561 schemdata[index].setContent(CONTENT_AIR);
565 for (size_t i = 0; i != splist->size(); i++) {
566 s16 y = (*splist)[i].first - p0.Y;
567 slice_probs[y] = (*splist)[i].second;
571 void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount,
572 std::vector<std::string> *usednodes, const NodeDefManager *ndef)
574 std::unordered_map<content_t, content_t> nodeidmap;
575 content_t numids = 0;
577 for (size_t i = 0; i != nodecount; i++) {
579 content_t c = nodes[i].getContent();
581 std::unordered_map<content_t, content_t>::const_iterator it =
583 if (it == nodeidmap.end()) {
587 usednodes->push_back(ndef->get(c).name);
588 nodeidmap.insert(std::make_pair(c, id));
592 nodes[i].setContent(id);