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 ///////////////////////////////////////////////////////////////////////////////
39 SchematicManager::SchematicManager(Server *server) :
40 ObjDefManager(server, OBJDEF_SCHEMATIC),
46 SchematicManager *SchematicManager::clone() const
48 auto mgr = new SchematicManager();
50 ObjDefManager::cloneTo(mgr);
55 void SchematicManager::clear()
57 EmergeManager *emerge = m_server->getEmergeManager();
59 // Remove all dangling references in Decorations
60 DecorationManager *decomgr = emerge->getWritableDecorationManager();
61 for (size_t i = 0; i != decomgr->getNumObjects(); i++) {
62 Decoration *deco = (Decoration *)decomgr->getRaw(i);
65 DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco);
67 dschem->schematic = NULL;
68 } catch (const std::bad_cast &) {
72 ObjDefManager::clear();
76 ///////////////////////////////////////////////////////////////////////////////
79 Schematic::~Schematic()
85 ObjDef *Schematic::clone() const
87 auto def = new Schematic();
89 NodeResolver::cloneTo(def);
91 def->c_nodes = c_nodes;
94 FATAL_ERROR_IF(!schemdata, "Schematic can only be cloned after loading");
95 u32 nodecount = size.X * size.Y * size.Z;
96 def->schemdata = new MapNode[nodecount];
97 memcpy(def->schemdata, schemdata, sizeof(MapNode) * nodecount);
98 def->slice_probs = new u8[size.Y];
99 memcpy(def->slice_probs, slice_probs, sizeof(u8) * size.Y);
105 void Schematic::resolveNodeNames()
108 getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
110 size_t bufsize = size.X * size.Y * size.Z;
111 for (size_t i = 0; i != bufsize; i++) {
112 content_t c_original = schemdata[i].getContent();
113 if (c_original >= c_nodes.size()) {
114 errorstream << "Corrupt schematic. name=\"" << name
115 << "\" at index " << i << std::endl;
118 // Unfold condensed ID layout to content_t
119 schemdata[i].setContent(c_nodes[c_original]);
124 void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place)
126 assert(schemdata && slice_probs);
127 sanity_check(m_ndef != NULL);
130 int ystride = size.X;
131 int zstride = size.X * size.Y;
137 int i_start, i_step_x, i_step_z;
146 i_start = zstride * (sz - 1) + sx - 1;
151 i_start = zstride * (sz - 1);
163 for (s16 y = 0; y != sy; y++) {
164 if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) &&
165 (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
168 for (s16 z = 0; z != sz; z++) {
169 u32 i = z * i_step_z + y * ystride + i_start;
170 for (s16 x = 0; x != sx; x++, i += i_step_x) {
171 v3s16 pos(p.X + x, y_map, p.Z + z);
172 if (!vm->m_area.contains(pos))
175 if (schemdata[i].getContent() == CONTENT_IGNORE)
178 u8 placement_prob = schemdata[i].param1 & MTSCHEM_PROB_MASK;
179 bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
181 if (placement_prob == MTSCHEM_PROB_NEVER)
184 u32 vi = vm->m_area.index(pos);
185 if (!force_place && !force_place_node) {
186 content_t c = vm->m_data[vi].getContent();
187 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
191 if ((placement_prob != MTSCHEM_PROB_ALWAYS) &&
192 (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
195 vm->m_data[vi] = schemdata[i];
196 vm->m_data[vi].param1 = 0;
199 vm->m_data[vi].rotateAlongYAxis(m_ndef, rot);
207 bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags,
208 Rotation rot, bool force_place)
211 assert(schemdata && slice_probs);
212 sanity_check(m_ndef != NULL);
214 //// Determine effective rotation and effective schematic dimensions
215 if (rot == ROTATE_RAND)
216 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
218 v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
219 v3s16(size.Z, size.Y, size.X) : size;
221 //// Adjust placement position if necessary
222 if (flags & DECO_PLACE_CENTER_X)
223 p.X -= (s.X - 1) / 2;
224 if (flags & DECO_PLACE_CENTER_Y)
225 p.Y -= (s.Y - 1) / 2;
226 if (flags & DECO_PLACE_CENTER_Z)
227 p.Z -= (s.Z - 1) / 2;
229 blitToVManip(vm, p, rot, force_place);
231 return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1)));
234 void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags,
235 Rotation rot, bool force_place)
237 std::map<v3s16, MapBlock *> lighting_modified_blocks;
238 std::map<v3s16, MapBlock *> modified_blocks;
239 std::map<v3s16, MapBlock *>::iterator it;
242 assert(schemdata != NULL);
243 sanity_check(m_ndef != NULL);
245 //// Determine effective rotation and effective schematic dimensions
246 if (rot == ROTATE_RAND)
247 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
249 v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
250 v3s16(size.Z, size.Y, size.X) : size;
252 //// Adjust placement position if necessary
253 if (flags & DECO_PLACE_CENTER_X)
254 p.X -= (s.X - 1) / 2;
255 if (flags & DECO_PLACE_CENTER_Y)
256 p.Y -= (s.Y - 1) / 2;
257 if (flags & DECO_PLACE_CENTER_Z)
258 p.Z -= (s.Z - 1) / 2;
260 //// Create VManip for effected area, emerge our area, modify area
261 //// inside VManip, then blit back.
262 v3s16 bp1 = getNodeBlockPos(p);
263 v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1, 1, 1));
266 vm.initialEmerge(bp1, bp2);
268 blitToVManip(&vm, p, rot, force_place);
270 voxalgo::blit_back_with_light(map, &vm, &modified_blocks);
272 //// Carry out post-map-modification actions
274 //// Create & dispatch map modification events to observers
276 event.type = MEET_OTHER;
277 for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it)
278 event.modified_blocks.insert(it->first);
280 map->dispatchEvent(event);
284 bool Schematic::deserializeFromMts(std::istream *is)
286 std::istream &ss = *is;
287 content_t cignore = CONTENT_IGNORE;
288 bool have_cignore = false;
291 u32 signature = readU32(ss);
292 if (signature != MTSCHEM_FILE_SIGNATURE) {
293 errorstream << __FUNCTION__ << ": invalid schematic "
299 u16 version = readU16(ss);
300 if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
301 errorstream << __FUNCTION__ << ": unsupported schematic "
302 "file version" << std::endl;
307 size = readV3S16(ss);
309 //// Read Y-slice probability values
310 delete []slice_probs;
311 slice_probs = new u8[size.Y];
312 for (int y = 0; y != size.Y; y++)
313 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD;
316 NodeResolver::reset();
318 u16 nidmapcount = readU16(ss);
319 for (int i = 0; i != nidmapcount; i++) {
320 std::string name = deSerializeString16(ss);
322 // Instances of "ignore" from v1 are converted to air (and instances
323 // are fixed to have MTSCHEM_PROB_NEVER later on).
324 if (name == "ignore") {
330 m_nodenames.push_back(name);
333 // Prepare for node resolver
334 m_nnlistsizes.push_back(m_nodenames.size());
337 size_t nodecount = size.X * size.Y * size.Z;
340 schemdata = new MapNode[nodecount];
342 MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata,
345 // Fix probability values for nodes that were ignore; removed in v2
347 for (size_t i = 0; i != nodecount; i++) {
348 if (schemdata[i].param1 == 0)
349 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD;
350 if (have_cignore && schemdata[i].getContent() == cignore)
351 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
355 // Fix probability values for probability range truncation introduced in v4
357 for (s16 y = 0; y != size.Y; y++)
358 slice_probs[y] >>= 1;
359 for (size_t i = 0; i != nodecount; i++)
360 schemdata[i].param1 >>= 1;
367 bool Schematic::serializeToMts(std::ostream *os) const
369 // Nodes must not be resolved (-> condensed)
370 // checking here is not possible because "schemdata" might be temporary.
372 std::ostream &ss = *os;
374 writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature
375 writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
376 writeV3S16(ss, size); // schematic size
378 for (int y = 0; y != size.Y; y++) // Y slice probabilities
379 writeU8(ss, slice_probs[y]);
381 writeU16(ss, m_nodenames.size()); // name count
382 for (size_t i = 0; i != m_nodenames.size(); i++) {
383 ss << serializeString16(m_nodenames[i]); // node names
386 // compressed bulk node data
387 MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE,
388 schemdata, size.X * size.Y * size.Z, 2, 2, -1);
394 bool Schematic::serializeToLua(std::ostream *os, bool use_comments,
395 u32 indent_spaces) const
397 std::ostream &ss = *os;
399 std::string indent("\t");
400 if (indent_spaces > 0)
401 indent.assign(indent_spaces, ' ');
403 bool resolve_done = isResolveDone();
404 FATAL_ERROR_IF(resolve_done && !m_ndef, "serializeToLua: NodeDefManager is required");
408 ss << "schematic = {" << std::endl;
409 ss << indent << "size = "
413 << "}," << std::endl;
416 //// Write y-slice probabilities
418 ss << indent << "yslice_prob = {" << std::endl;
420 for (u16 y = 0; y != size.Y; y++) {
421 u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK;
423 ss << indent << indent << "{"
425 << ", prob=" << (u16)probability * 2
426 << "}," << std::endl;
429 ss << indent << "}," << std::endl;
434 ss << indent << "data = {" << std::endl;
437 for (u16 z = 0; z != size.Z; z++)
438 for (u16 y = 0; y != size.Y; y++) {
443 << ", y=" << y << std::endl;
446 for (u16 x = 0; x != size.X; x++, i++) {
447 u8 probability = schemdata[i].param1 & MTSCHEM_PROB_MASK;
448 bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
450 // After node resolving: real content_t, lookup using NodeDefManager
451 // Prior node resolving: condensed ID, lookup using m_nodenames
452 content_t c = schemdata[i].getContent();
454 ss << indent << indent << "{" << "name=\"";
457 // Prior node resolving (eg. direct schematic load)
458 FATAL_ERROR_IF(c >= m_nodenames.size(), "Invalid node list");
459 ss << m_nodenames[c];
461 // After node resolving (eg. biome decoration)
462 ss << m_ndef->get(c).name;
465 ss << "\", prob=" << (u16)probability * 2
466 << ", param2=" << (u16)schemdata[i].param2;
469 ss << ", force_place=true";
471 ss << "}," << std::endl;
475 ss << indent << "}," << std::endl;
478 ss << "}" << std::endl;
484 bool Schematic::loadSchematicFromFile(const std::string &filename,
485 const NodeDefManager *ndef, StringMap *replace_names)
487 std::ifstream is(filename.c_str(), std::ios_base::binary);
489 errorstream << __FUNCTION__ << ": unable to open file '"
490 << filename << "'" << std::endl;
497 if (!deserializeFromMts(&is))
503 for (std::string &node_name : m_nodenames) {
504 StringMap::iterator it = replace_names->find(node_name);
505 if (it != replace_names->end())
506 node_name = it->second;
511 m_ndef->pendNodeResolve(this);
517 bool Schematic::saveSchematicToFile(const std::string &filename,
518 const NodeDefManager *ndef)
520 Schematic *schem = this;
522 bool needs_condense = isResolveDone();
527 if (needs_condense) {
531 schem = (Schematic *)this->clone();
532 schem->condenseContentIds();
535 std::ostringstream os(std::ios_base::binary);
536 bool status = schem->serializeToMts(&os);
544 return fs::safeWriteToFile(filename, os.str());
548 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
550 MMVManip *vm = new MMVManip(map);
552 v3s16 bp1 = getNodeBlockPos(p1);
553 v3s16 bp2 = getNodeBlockPos(p2);
554 vm->initialEmerge(bp1, bp2);
558 slice_probs = new u8[size.Y];
559 for (s16 y = 0; y != size.Y; y++)
560 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
562 schemdata = new MapNode[size.X * size.Y * size.Z];
565 for (s16 z = p1.Z; z <= p2.Z; z++)
566 for (s16 y = p1.Y; y <= p2.Y; y++) {
567 u32 vi = vm->m_area.index(p1.X, y, z);
568 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
569 schemdata[i] = vm->m_data[vi];
570 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
576 // Reset and mark as complete
577 NodeResolver::reset(true);
583 void Schematic::applyProbabilities(v3s16 p0,
584 std::vector<std::pair<v3s16, u8> > *plist,
585 std::vector<std::pair<s16, u8> > *splist)
587 for (size_t i = 0; i != plist->size(); i++) {
588 v3s16 p = (*plist)[i].first - p0;
589 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
590 if (index < size.Z * size.Y * size.X) {
591 u8 prob = (*plist)[i].second;
592 schemdata[index].param1 = prob;
594 // trim unnecessary node names from schematic
595 if (prob == MTSCHEM_PROB_NEVER)
596 schemdata[index].setContent(CONTENT_AIR);
600 for (size_t i = 0; i != splist->size(); i++) {
601 s16 y = (*splist)[i].first - p0.Y;
602 slice_probs[y] = (*splist)[i].second;
607 void Schematic::condenseContentIds()
609 std::unordered_map<content_t, content_t> nodeidmap;
610 content_t numids = 0;
612 // Reset node resolve fields
613 NodeResolver::reset();
615 size_t nodecount = size.X * size.Y * size.Z;
616 for (size_t i = 0; i != nodecount; i++) {
618 content_t c = schemdata[i].getContent();
620 auto it = nodeidmap.find(c);
621 if (it == nodeidmap.end()) {
625 m_nodenames.push_back(m_ndef->get(c).name);
626 nodeidmap.emplace(std::make_pair(c, id));
630 schemdata[i].setContent(id);