mapblock.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "mapblock.h"
  17. #include <sstream>
  18. #include "map.h"
  19. #include "light.h"
  20. #include "nodedef.h"
  21. #include "nodemetadata.h"
  22. #include "gamedef.h"
  23. #include "log.h"
  24. #include "nameidmapping.h"
  25. #include "content_mapnode.h" // For legacy name-id mapping
  26. #include "content_nodemeta.h" // For legacy deserialization
  27. #include "serialization.h"
  28. #ifndef SERVER
  29. #include "client/mapblock_mesh.h"
  30. #endif
  31. #include "porting.h"
  32. #include "util/string.h"
  33. #include "util/serialize.h"
  34. #include "util/basic_macros.h"
  35. static const char *modified_reason_strings[] = {
  36. "initial",
  37. "reallocate",
  38. "setIsUnderground",
  39. "setLightingExpired",
  40. "setGenerated",
  41. "setNode",
  42. "setNodeNoCheck",
  43. "setTimestamp",
  44. "NodeMetaRef::reportMetadataChange",
  45. "clearAllObjects",
  46. "Timestamp expired (step)",
  47. "addActiveObjectRaw",
  48. "removeRemovedObjects/remove",
  49. "removeRemovedObjects/deactivate",
  50. "Stored list cleared in activateObjects due to overflow",
  51. "deactivateFarObjects: Static data moved in",
  52. "deactivateFarObjects: Static data moved out",
  53. "deactivateFarObjects: Static data changed considerably",
  54. "finishBlockMake: expireDayNightDiff",
  55. "unknown",
  56. };
  57. /*
  58. MapBlock
  59. */
  60. MapBlock::MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef):
  61. m_parent(parent),
  62. m_pos(pos),
  63. m_pos_relative(pos * MAP_BLOCKSIZE),
  64. m_gamedef(gamedef)
  65. {
  66. reallocate();
  67. }
  68. MapBlock::~MapBlock()
  69. {
  70. #ifndef SERVER
  71. {
  72. delete mesh;
  73. mesh = nullptr;
  74. }
  75. #endif
  76. }
  77. bool MapBlock::onObjectsActivation()
  78. {
  79. // Ignore if no stored objects (to not set changed flag)
  80. if (m_static_objects.getAllStored().empty())
  81. return false;
  82. verbosestream << "MapBlock::onObjectsActivation(): "
  83. << "activating objects of block " << PP(getPos()) << " ("
  84. << m_static_objects.getStoredSize() << " objects)" << std::endl;
  85. if (m_static_objects.getStoredSize() > g_settings->getU16("max_objects_per_block")) {
  86. errorstream << "suspiciously large amount of objects detected: "
  87. << m_static_objects.getStoredSize() << " in "
  88. << PP(getPos()) << "; removing all of them." << std::endl;
  89. // Clear stored list
  90. m_static_objects.clearStored();
  91. raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_TOO_MANY_OBJECTS);
  92. return false;
  93. }
  94. return true;
  95. }
  96. bool MapBlock::saveStaticObject(u16 id, const StaticObject &obj, u32 reason)
  97. {
  98. if (m_static_objects.getStoredSize() >= g_settings->getU16("max_objects_per_block")) {
  99. warningstream << "MapBlock::saveStaticObject(): Trying to store id = " << id
  100. << " statically but block " << PP(getPos()) << " already contains "
  101. << m_static_objects.getStoredSize() << " objects."
  102. << std::endl;
  103. return false;
  104. }
  105. m_static_objects.insert(id, obj);
  106. if (reason != MOD_REASON_UNKNOWN) // Do not mark as modified if requested
  107. raiseModified(MOD_STATE_WRITE_NEEDED, reason);
  108. return true;
  109. }
  110. // This method is only for Server, don't call it on client
  111. void MapBlock::step(float dtime, const std::function<bool(v3s16, MapNode, f32)> &on_timer_cb)
  112. {
  113. // Run script callbacks for elapsed node_timers
  114. std::vector<NodeTimer> elapsed_timers = m_node_timers.step(dtime);
  115. if (!elapsed_timers.empty()) {
  116. MapNode n;
  117. v3s16 p;
  118. for (const NodeTimer &elapsed_timer : elapsed_timers) {
  119. n = getNodeNoEx(elapsed_timer.position);
  120. p = elapsed_timer.position + getPosRelative();
  121. if (on_timer_cb(p, n, elapsed_timer.elapsed))
  122. setNodeTimer(NodeTimer(elapsed_timer.timeout, 0, elapsed_timer.position));
  123. }
  124. }
  125. }
  126. bool MapBlock::isValidPositionParent(v3s16 p)
  127. {
  128. if (isValidPosition(p)) {
  129. return true;
  130. }
  131. return m_parent->isValidPosition(getPosRelative() + p);
  132. }
  133. MapNode MapBlock::getNodeParent(v3s16 p, bool *is_valid_position)
  134. {
  135. if (!isValidPosition(p))
  136. return m_parent->getNode(getPosRelative() + p, is_valid_position);
  137. if (is_valid_position)
  138. *is_valid_position = true;
  139. return data[p.Z * zstride + p.Y * ystride + p.X];
  140. }
  141. std::string MapBlock::getModifiedReasonString()
  142. {
  143. std::string reason;
  144. const u32 ubound = MYMIN(sizeof(m_modified_reason) * CHAR_BIT,
  145. ARRLEN(modified_reason_strings));
  146. for (u32 i = 0; i != ubound; i++) {
  147. if ((m_modified_reason & (1 << i)) == 0)
  148. continue;
  149. reason += modified_reason_strings[i];
  150. reason += ", ";
  151. }
  152. if (reason.length() > 2)
  153. reason.resize(reason.length() - 2);
  154. return reason;
  155. }
  156. void MapBlock::copyTo(VoxelManipulator &dst)
  157. {
  158. v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
  159. VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
  160. // Copy from data to VoxelManipulator
  161. dst.copyFrom(data, data_area, v3s16(0,0,0),
  162. getPosRelative(), data_size);
  163. }
  164. void MapBlock::copyFrom(VoxelManipulator &dst)
  165. {
  166. v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
  167. VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
  168. // Copy from VoxelManipulator to data
  169. dst.copyTo(data, data_area, v3s16(0,0,0),
  170. getPosRelative(), data_size);
  171. }
  172. void MapBlock::actuallyUpdateDayNightDiff()
  173. {
  174. const NodeDefManager *nodemgr = m_gamedef->ndef();
  175. // Running this function un-expires m_day_night_differs
  176. m_day_night_differs_expired = false;
  177. bool differs = false;
  178. /*
  179. Check if any lighting value differs
  180. */
  181. MapNode previous_n(CONTENT_IGNORE);
  182. for (u32 i = 0; i < nodecount; i++) {
  183. MapNode n = data[i];
  184. // If node is identical to previous node, don't verify if it differs
  185. if (n == previous_n)
  186. continue;
  187. differs = !n.isLightDayNightEq(nodemgr->getLightingFlags(n));
  188. if (differs)
  189. break;
  190. previous_n = n;
  191. }
  192. /*
  193. If some lighting values differ, check if the whole thing is
  194. just air. If it is just air, differs = false
  195. */
  196. if (differs) {
  197. bool only_air = true;
  198. for (u32 i = 0; i < nodecount; i++) {
  199. MapNode &n = data[i];
  200. if (n.getContent() != CONTENT_AIR) {
  201. only_air = false;
  202. break;
  203. }
  204. }
  205. if (only_air)
  206. differs = false;
  207. }
  208. // Set member variable
  209. m_day_night_differs = differs;
  210. }
  211. void MapBlock::expireDayNightDiff()
  212. {
  213. m_day_night_differs_expired = true;
  214. }
  215. /*
  216. Serialization
  217. */
  218. // List relevant id-name pairs for ids in the block using nodedef
  219. // Renumbers the content IDs (starting at 0 and incrementing)
  220. static void getBlockNodeIdMapping(NameIdMapping *nimap, MapNode *nodes,
  221. const NodeDefManager *nodedef)
  222. {
  223. // The static memory requires about 65535 * sizeof(int) RAM in order to be
  224. // sure we can handle all content ids. But it's absolutely worth it as it's
  225. // a speedup of 4 for one of the major time consuming functions on storing
  226. // mapblocks.
  227. thread_local std::unique_ptr<content_t[]> mapping;
  228. static_assert(sizeof(content_t) == 2, "content_t must be 16-bit");
  229. if (!mapping)
  230. mapping = std::make_unique<content_t[]>(USHRT_MAX + 1);
  231. memset(mapping.get(), 0xFF, (USHRT_MAX + 1) * sizeof(content_t));
  232. std::unordered_set<content_t> unknown_contents;
  233. content_t id_counter = 0;
  234. for (u32 i = 0; i < MapBlock::nodecount; i++) {
  235. content_t global_id = nodes[i].getContent();
  236. content_t id = CONTENT_IGNORE;
  237. // Try to find an existing mapping
  238. if (mapping[global_id] != 0xFFFF) {
  239. id = mapping[global_id];
  240. } else {
  241. // We have to assign a new mapping
  242. id = id_counter++;
  243. mapping[global_id] = id;
  244. const ContentFeatures &f = nodedef->get(global_id);
  245. const std::string &name = f.name;
  246. if (name.empty())
  247. unknown_contents.insert(global_id);
  248. else
  249. nimap->set(id, name);
  250. }
  251. // Update the MapNode
  252. nodes[i].setContent(id);
  253. }
  254. for (u16 unknown_content : unknown_contents) {
  255. errorstream << "getBlockNodeIdMapping(): IGNORING ERROR: "
  256. << "Name for node id " << unknown_content << " not known" << std::endl;
  257. }
  258. }
  259. // Correct ids in the block to match nodedef based on names.
  260. // Unknown ones are added to nodedef.
  261. // Will not update itself to match id-name pairs in nodedef.
  262. static void correctBlockNodeIds(const NameIdMapping *nimap, MapNode *nodes,
  263. IGameDef *gamedef)
  264. {
  265. const NodeDefManager *nodedef = gamedef->ndef();
  266. // This means the block contains incorrect ids, and we contain
  267. // the information to convert those to names.
  268. // nodedef contains information to convert our names to globally
  269. // correct ids.
  270. std::unordered_set<content_t> unnamed_contents;
  271. std::unordered_set<std::string> unallocatable_contents;
  272. bool previous_exists = false;
  273. content_t previous_local_id = CONTENT_IGNORE;
  274. content_t previous_global_id = CONTENT_IGNORE;
  275. for (u32 i = 0; i < MapBlock::nodecount; i++) {
  276. content_t local_id = nodes[i].getContent();
  277. // If previous node local_id was found and same than before, don't lookup maps
  278. // apply directly previous resolved id
  279. // This permits to massively improve loading performance when nodes are similar
  280. // example: default:air, default:stone are massively present
  281. if (previous_exists && local_id == previous_local_id) {
  282. nodes[i].setContent(previous_global_id);
  283. continue;
  284. }
  285. std::string name;
  286. if (!nimap->getName(local_id, name)) {
  287. unnamed_contents.insert(local_id);
  288. previous_exists = false;
  289. continue;
  290. }
  291. content_t global_id;
  292. if (!nodedef->getId(name, global_id)) {
  293. global_id = gamedef->allocateUnknownNodeId(name);
  294. if (global_id == CONTENT_IGNORE) {
  295. unallocatable_contents.insert(name);
  296. previous_exists = false;
  297. continue;
  298. }
  299. }
  300. nodes[i].setContent(global_id);
  301. // Save previous node local_id & global_id result
  302. previous_local_id = local_id;
  303. previous_global_id = global_id;
  304. previous_exists = true;
  305. }
  306. for (const content_t c: unnamed_contents) {
  307. errorstream << "correctBlockNodeIds(): IGNORING ERROR: "
  308. << "Block contains id " << c
  309. << " with no name mapping" << std::endl;
  310. }
  311. for (const std::string &node_name: unallocatable_contents) {
  312. errorstream << "correctBlockNodeIds(): IGNORING ERROR: "
  313. << "Could not allocate global id for node name \""
  314. << node_name << "\"" << std::endl;
  315. }
  316. }
  317. void MapBlock::serialize(std::ostream &os_compressed, u8 version, bool disk, int compression_level)
  318. {
  319. if(!ser_ver_supported(version))
  320. throw VersionMismatchException("ERROR: MapBlock format not supported");
  321. FATAL_ERROR_IF(version < SER_FMT_VER_LOWEST_WRITE, "Serialization version error");
  322. std::ostringstream os_raw(std::ios_base::binary);
  323. std::ostream &os = version >= 29 ? os_raw : os_compressed;
  324. // First byte
  325. u8 flags = 0;
  326. if(is_underground)
  327. flags |= 0x01;
  328. if(getDayNightDiff())
  329. flags |= 0x02;
  330. if (!m_generated)
  331. flags |= 0x08;
  332. writeU8(os, flags);
  333. if (version >= 27) {
  334. writeU16(os, m_lighting_complete);
  335. }
  336. /*
  337. Bulk node data
  338. */
  339. NameIdMapping nimap;
  340. SharedBuffer<u8> buf;
  341. const u8 content_width = 2;
  342. const u8 params_width = 2;
  343. if(disk)
  344. {
  345. MapNode *tmp_nodes = new MapNode[nodecount];
  346. memcpy(tmp_nodes, data, nodecount * sizeof(MapNode));
  347. getBlockNodeIdMapping(&nimap, tmp_nodes, m_gamedef->ndef());
  348. buf = MapNode::serializeBulk(version, tmp_nodes, nodecount,
  349. content_width, params_width);
  350. delete[] tmp_nodes;
  351. // write timestamp and node/id mapping first
  352. if (version >= 29) {
  353. writeU32(os, getTimestamp());
  354. nimap.serialize(os);
  355. }
  356. }
  357. else
  358. {
  359. buf = MapNode::serializeBulk(version, data, nodecount,
  360. content_width, params_width);
  361. }
  362. writeU8(os, content_width);
  363. writeU8(os, params_width);
  364. if (version >= 29) {
  365. os.write(reinterpret_cast<char*>(*buf), buf.getSize());
  366. } else {
  367. // prior to 29 node data was compressed individually
  368. compress(buf, os, version, compression_level);
  369. }
  370. /*
  371. Node metadata
  372. */
  373. if (version >= 29) {
  374. m_node_metadata.serialize(os, version, disk);
  375. } else {
  376. // use os_raw from above to avoid allocating another stream object
  377. m_node_metadata.serialize(os_raw, version, disk);
  378. // prior to 29 node data was compressed individually
  379. compress(os_raw.str(), os, version, compression_level);
  380. }
  381. /*
  382. Data that goes to disk, but not the network
  383. */
  384. if (disk) {
  385. if (version <= 24) {
  386. // Node timers
  387. m_node_timers.serialize(os, version);
  388. }
  389. // Static objects
  390. m_static_objects.serialize(os);
  391. if (version < 29) {
  392. // Timestamp
  393. writeU32(os, getTimestamp());
  394. // Write block-specific node definition id mapping
  395. nimap.serialize(os);
  396. }
  397. if (version >= 25) {
  398. // Node timers
  399. m_node_timers.serialize(os, version);
  400. }
  401. }
  402. if (version >= 29) {
  403. // now compress the whole thing
  404. compress(os_raw.str(), os_compressed, version, compression_level);
  405. }
  406. }
  407. void MapBlock::serializeNetworkSpecific(std::ostream &os)
  408. {
  409. writeU8(os, 2); // version
  410. }
  411. void MapBlock::deSerialize(std::istream &in_compressed, u8 version, bool disk)
  412. {
  413. if(!ser_ver_supported(version))
  414. throw VersionMismatchException("ERROR: MapBlock format not supported");
  415. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())<<std::endl);
  416. m_day_night_differs_expired = false;
  417. if(version <= 21)
  418. {
  419. deSerialize_pre22(in_compressed, version, disk);
  420. return;
  421. }
  422. // Decompress the whole block (version >= 29)
  423. std::stringstream in_raw(std::ios_base::binary | std::ios_base::in | std::ios_base::out);
  424. if (version >= 29)
  425. decompress(in_compressed, in_raw, version);
  426. std::istream &is = version >= 29 ? in_raw : in_compressed;
  427. u8 flags = readU8(is);
  428. is_underground = (flags & 0x01) != 0;
  429. m_day_night_differs = (flags & 0x02) != 0;
  430. if (version < 27)
  431. m_lighting_complete = 0xFFFF;
  432. else
  433. m_lighting_complete = readU16(is);
  434. m_generated = (flags & 0x08) == 0;
  435. NameIdMapping nimap;
  436. if (disk && version >= 29) {
  437. // Timestamp
  438. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  439. <<": Timestamp"<<std::endl);
  440. setTimestampNoChangedFlag(readU32(is));
  441. m_disk_timestamp = m_timestamp;
  442. // Node/id mapping
  443. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  444. <<": NameIdMapping"<<std::endl);
  445. nimap.deSerialize(is);
  446. }
  447. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  448. <<": Bulk node data"<<std::endl);
  449. u8 content_width = readU8(is);
  450. u8 params_width = readU8(is);
  451. if(content_width != 1 && content_width != 2)
  452. throw SerializationError("MapBlock::deSerialize(): invalid content_width");
  453. if(params_width != 2)
  454. throw SerializationError("MapBlock::deSerialize(): invalid params_width");
  455. /*
  456. Bulk node data
  457. */
  458. if (version >= 29) {
  459. MapNode::deSerializeBulk(is, version, data, nodecount,
  460. content_width, params_width);
  461. } else {
  462. // use in_raw from above to avoid allocating another stream object
  463. decompress(is, in_raw, version);
  464. MapNode::deSerializeBulk(in_raw, version, data, nodecount,
  465. content_width, params_width);
  466. }
  467. /*
  468. NodeMetadata
  469. */
  470. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  471. <<": Node metadata"<<std::endl);
  472. if (version >= 29) {
  473. m_node_metadata.deSerialize(is, m_gamedef->idef());
  474. } else {
  475. try {
  476. // reuse in_raw
  477. in_raw.str("");
  478. in_raw.clear();
  479. decompress(is, in_raw, version);
  480. if (version >= 23)
  481. m_node_metadata.deSerialize(in_raw, m_gamedef->idef());
  482. else
  483. content_nodemeta_deserialize_legacy(in_raw,
  484. &m_node_metadata, &m_node_timers,
  485. m_gamedef->idef());
  486. } catch(SerializationError &e) {
  487. warningstream<<"MapBlock::deSerialize(): Ignoring an error"
  488. <<" while deserializing node metadata at ("
  489. <<PP(getPos())<<": "<<e.what()<<std::endl;
  490. }
  491. }
  492. /*
  493. Data that is only on disk
  494. */
  495. if (disk) {
  496. // Node timers
  497. if (version == 23) {
  498. // Read unused zero
  499. readU8(is);
  500. }
  501. if (version == 24) {
  502. TRACESTREAM(<< "MapBlock::deSerialize " << PP(getPos())
  503. << ": Node timers (ver==24)" << std::endl);
  504. m_node_timers.deSerialize(is, version);
  505. }
  506. // Static objects
  507. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  508. <<": Static objects"<<std::endl);
  509. m_static_objects.deSerialize(is);
  510. if (version < 29) {
  511. // Timestamp
  512. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  513. <<": Timestamp"<<std::endl);
  514. setTimestampNoChangedFlag(readU32(is));
  515. m_disk_timestamp = m_timestamp;
  516. // Node/id mapping
  517. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  518. <<": NameIdMapping"<<std::endl);
  519. nimap.deSerialize(is);
  520. }
  521. // Dynamically re-set ids based on node names
  522. correctBlockNodeIds(&nimap, data, m_gamedef);
  523. if(version >= 25){
  524. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  525. <<": Node timers (ver>=25)"<<std::endl);
  526. m_node_timers.deSerialize(is, version);
  527. }
  528. }
  529. TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
  530. <<": Done."<<std::endl);
  531. }
  532. void MapBlock::deSerializeNetworkSpecific(std::istream &is)
  533. {
  534. try {
  535. readU8(is);
  536. //const u8 version = readU8(is);
  537. //if (version != 1)
  538. //throw SerializationError("unsupported MapBlock version");
  539. } catch(SerializationError &e) {
  540. warningstream<<"MapBlock::deSerializeNetworkSpecific(): Ignoring an error"
  541. <<": "<<e.what()<<std::endl;
  542. }
  543. }
  544. bool MapBlock::storeActiveObject(u16 id)
  545. {
  546. if (m_static_objects.storeActiveObject(id)) {
  547. raiseModified(MOD_STATE_WRITE_NEEDED,
  548. MOD_REASON_REMOVE_OBJECTS_DEACTIVATE);
  549. return true;
  550. }
  551. return false;
  552. }
  553. u32 MapBlock::clearObjects()
  554. {
  555. u32 size = m_static_objects.size();
  556. if (size > 0) {
  557. m_static_objects.clear();
  558. raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_CLEAR_ALL_OBJECTS);
  559. }
  560. return size;
  561. }
  562. /*
  563. Legacy serialization
  564. */
  565. void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk)
  566. {
  567. // Initialize default flags
  568. is_underground = false;
  569. m_day_night_differs = false;
  570. m_lighting_complete = 0xFFFF;
  571. m_generated = true;
  572. // Make a temporary buffer
  573. u32 ser_length = MapNode::serializedLength(version);
  574. SharedBuffer<u8> databuf_nodelist(nodecount * ser_length);
  575. // These have no compression
  576. if (version <= 3 || version == 5 || version == 6) {
  577. char tmp;
  578. is.read(&tmp, 1);
  579. if (is.gcount() != 1)
  580. throw SerializationError(std::string(FUNCTION_NAME)
  581. + ": not enough input data");
  582. is_underground = tmp;
  583. is.read((char *)*databuf_nodelist, nodecount * ser_length);
  584. if ((u32)is.gcount() != nodecount * ser_length)
  585. throw SerializationError(std::string(FUNCTION_NAME)
  586. + ": not enough input data");
  587. } else if (version <= 10) {
  588. u8 t8;
  589. is.read((char *)&t8, 1);
  590. is_underground = t8;
  591. {
  592. // Uncompress and set material data
  593. std::ostringstream os(std::ios_base::binary);
  594. decompress(is, os, version);
  595. std::string s = os.str();
  596. if (s.size() != nodecount)
  597. throw SerializationError(std::string(FUNCTION_NAME)
  598. + ": not enough input data");
  599. for (u32 i = 0; i < s.size(); i++) {
  600. databuf_nodelist[i*ser_length] = s[i];
  601. }
  602. }
  603. {
  604. // Uncompress and set param data
  605. std::ostringstream os(std::ios_base::binary);
  606. decompress(is, os, version);
  607. std::string s = os.str();
  608. if (s.size() != nodecount)
  609. throw SerializationError(std::string(FUNCTION_NAME)
  610. + ": not enough input data");
  611. for (u32 i = 0; i < s.size(); i++) {
  612. databuf_nodelist[i*ser_length + 1] = s[i];
  613. }
  614. }
  615. if (version >= 10) {
  616. // Uncompress and set param2 data
  617. std::ostringstream os(std::ios_base::binary);
  618. decompress(is, os, version);
  619. std::string s = os.str();
  620. if (s.size() != nodecount)
  621. throw SerializationError(std::string(FUNCTION_NAME)
  622. + ": not enough input data");
  623. for (u32 i = 0; i < s.size(); i++) {
  624. databuf_nodelist[i*ser_length + 2] = s[i];
  625. }
  626. }
  627. } else { // All other versions (10 to 21)
  628. u8 flags;
  629. is.read((char*)&flags, 1);
  630. is_underground = (flags & 0x01) != 0;
  631. m_day_night_differs = (flags & 0x02) != 0;
  632. if (version >= 18)
  633. m_generated = (flags & 0x08) == 0;
  634. // Uncompress data
  635. std::ostringstream os(std::ios_base::binary);
  636. decompress(is, os, version);
  637. std::string s = os.str();
  638. if (s.size() != nodecount * 3)
  639. throw SerializationError(std::string(FUNCTION_NAME)
  640. + ": decompress resulted in size other than nodecount*3");
  641. // deserialize nodes from buffer
  642. for (u32 i = 0; i < nodecount; i++) {
  643. databuf_nodelist[i*ser_length] = s[i];
  644. databuf_nodelist[i*ser_length + 1] = s[i+nodecount];
  645. databuf_nodelist[i*ser_length + 2] = s[i+nodecount*2];
  646. }
  647. /*
  648. NodeMetadata
  649. */
  650. if (version >= 14) {
  651. // Ignore errors
  652. try {
  653. if (version <= 15) {
  654. std::string data = deSerializeString16(is);
  655. std::istringstream iss(data, std::ios_base::binary);
  656. content_nodemeta_deserialize_legacy(iss,
  657. &m_node_metadata, &m_node_timers,
  658. m_gamedef->idef());
  659. } else {
  660. //std::string data = deSerializeString32(is);
  661. std::ostringstream oss(std::ios_base::binary);
  662. decompressZlib(is, oss);
  663. std::istringstream iss(oss.str(), std::ios_base::binary);
  664. content_nodemeta_deserialize_legacy(iss,
  665. &m_node_metadata, &m_node_timers,
  666. m_gamedef->idef());
  667. }
  668. } catch(SerializationError &e) {
  669. warningstream<<"MapBlock::deSerialize(): Ignoring an error"
  670. <<" while deserializing node metadata"<<std::endl;
  671. }
  672. }
  673. }
  674. // Deserialize node data
  675. for (u32 i = 0; i < nodecount; i++) {
  676. data[i].deSerialize(&databuf_nodelist[i * ser_length], version);
  677. }
  678. if (disk) {
  679. /*
  680. Versions up from 9 have block objects. (DEPRECATED)
  681. */
  682. if (version >= 9) {
  683. u16 count = readU16(is);
  684. // Not supported and length not known if count is not 0
  685. if(count != 0){
  686. warningstream<<"MapBlock::deSerialize_pre22(): "
  687. <<"Ignoring stuff coming at and after MBOs"<<std::endl;
  688. return;
  689. }
  690. }
  691. /*
  692. Versions up from 15 have static objects.
  693. */
  694. if (version >= 15)
  695. m_static_objects.deSerialize(is);
  696. // Timestamp
  697. if (version >= 17) {
  698. setTimestampNoChangedFlag(readU32(is));
  699. m_disk_timestamp = m_timestamp;
  700. } else {
  701. setTimestampNoChangedFlag(BLOCK_TIMESTAMP_UNDEFINED);
  702. }
  703. // Dynamically re-set ids based on node names
  704. NameIdMapping nimap;
  705. // If supported, read node definition id mapping
  706. if (version >= 21) {
  707. nimap.deSerialize(is);
  708. // Else set the legacy mapping
  709. } else {
  710. content_mapnode_get_name_id_mapping(&nimap);
  711. }
  712. correctBlockNodeIds(&nimap, data, m_gamedef);
  713. }
  714. // Legacy data changes
  715. // This code has to convert from pre-22 to post-22 format.
  716. const NodeDefManager *nodedef = m_gamedef->ndef();
  717. for (u32 i = 0; i < nodecount; i++) {
  718. const ContentFeatures &f = nodedef->get(data[i].getContent());
  719. // Mineral
  720. if(nodedef->getId("default:stone") == data[i].getContent()
  721. && data[i].getParam1() == 1)
  722. {
  723. data[i].setContent(nodedef->getId("default:stone_with_coal"));
  724. data[i].setParam1(0);
  725. }
  726. else if(nodedef->getId("default:stone") == data[i].getContent()
  727. && data[i].getParam1() == 2)
  728. {
  729. data[i].setContent(nodedef->getId("default:stone_with_iron"));
  730. data[i].setParam1(0);
  731. }
  732. // facedir_simple
  733. if (f.legacy_facedir_simple) {
  734. data[i].setParam2(data[i].getParam1());
  735. data[i].setParam1(0);
  736. }
  737. // wall_mounted
  738. if (f.legacy_wallmounted) {
  739. u8 wallmounted_new_to_old[8] = {0x04, 0x08, 0x01, 0x02, 0x10, 0x20, 0, 0};
  740. u8 dir_old_format = data[i].getParam2();
  741. u8 dir_new_format = 0;
  742. for (u8 j = 0; j < 8; j++) {
  743. if ((dir_old_format & wallmounted_new_to_old[j]) != 0) {
  744. dir_new_format = j;
  745. break;
  746. }
  747. }
  748. data[i].setParam2(dir_new_format);
  749. }
  750. }
  751. }
  752. /*
  753. Get a quick string to describe what a block actually contains
  754. */
  755. std::string analyze_block(MapBlock *block)
  756. {
  757. if (block == NULL)
  758. return "NULL";
  759. std::ostringstream desc;
  760. v3s16 p = block->getPos();
  761. char spos[25];
  762. porting::mt_snprintf(spos, sizeof(spos), "(%2d,%2d,%2d), ", p.X, p.Y, p.Z);
  763. desc<<spos;
  764. switch(block->getModified())
  765. {
  766. case MOD_STATE_CLEAN:
  767. desc<<"CLEAN, ";
  768. break;
  769. case MOD_STATE_WRITE_AT_UNLOAD:
  770. desc<<"WRITE_AT_UNLOAD, ";
  771. break;
  772. case MOD_STATE_WRITE_NEEDED:
  773. desc<<"WRITE_NEEDED, ";
  774. break;
  775. default:
  776. desc<<"unknown getModified()="+itos(block->getModified())+", ";
  777. }
  778. if(block->isGenerated())
  779. desc<<"is_gen [X], ";
  780. else
  781. desc<<"is_gen [ ], ";
  782. if(block->getIsUnderground())
  783. desc<<"is_ug [X], ";
  784. else
  785. desc<<"is_ug [ ], ";
  786. desc<<"lighting_complete: "<<block->getLightingComplete()<<", ";
  787. bool full_ignore = true;
  788. bool some_ignore = false;
  789. bool full_air = true;
  790. bool some_air = false;
  791. for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
  792. for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
  793. for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
  794. {
  795. v3s16 p(x0,y0,z0);
  796. MapNode n = block->getNodeNoEx(p);
  797. content_t c = n.getContent();
  798. if(c == CONTENT_IGNORE)
  799. some_ignore = true;
  800. else
  801. full_ignore = false;
  802. if(c == CONTENT_AIR)
  803. some_air = true;
  804. else
  805. full_air = false;
  806. }
  807. desc<<"content {";
  808. std::ostringstream ss;
  809. if(full_ignore)
  810. ss<<"IGNORE (full), ";
  811. else if(some_ignore)
  812. ss<<"IGNORE, ";
  813. if(full_air)
  814. ss<<"AIR (full), ";
  815. else if(some_air)
  816. ss<<"AIR, ";
  817. if(ss.str().size()>=2)
  818. desc<<ss.str().substr(0, ss.str().size()-2);
  819. desc<<"}, ";
  820. return desc.str().substr(0, desc.str().size()-2);
  821. }
  822. //END