/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "map.h" #include "mapsector.h" #include "mapblock.h" #include "filesys.h" #include "voxel.h" #include "voxelalgorithms.h" #include "porting.h" #include "serialization.h" #include "nodemetadata.h" #include "settings.h" #include "log.h" #include "profiler.h" #include "nodedef.h" #include "gamedef.h" #include "util/directiontables.h" #include "util/basic_macros.h" #include "rollback_interface.h" #include "environment.h" #include "reflowscan.h" #include "emerge.h" #include "mapgen/mapgen_v6.h" #include "mapgen/mg_biome.h" #include "config.h" #include "server.h" #include "database/database.h" #include "database/database-dummy.h" #include "database/database-sqlite3.h" #include "script/scripting_server.h" #include #include #if USE_LEVELDB #include "database/database-leveldb.h" #endif #if USE_REDIS #include "database/database-redis.h" #endif #if USE_POSTGRESQL #include "database/database-postgresql.h" #endif /* Map */ Map::Map(IGameDef *gamedef): m_gamedef(gamedef), m_nodedef(gamedef->ndef()) { } Map::~Map() { /* Free all MapSectors */ for (auto §or : m_sectors) { delete sector.second; } } void Map::addEventReceiver(MapEventReceiver *event_receiver) { m_event_receivers.insert(event_receiver); } void Map::removeEventReceiver(MapEventReceiver *event_receiver) { m_event_receivers.erase(event_receiver); } void Map::dispatchEvent(const MapEditEvent &event) { for (MapEventReceiver *event_receiver : m_event_receivers) { event_receiver->onMapEditEvent(event); } } MapSector * Map::getSectorNoGenerateNoLock(v2s16 p) { if(m_sector_cache != NULL && p == m_sector_cache_p){ MapSector * sector = m_sector_cache; return sector; } std::map::iterator n = m_sectors.find(p); if (n == m_sectors.end()) return NULL; MapSector *sector = n->second; // Cache the last result m_sector_cache_p = p; m_sector_cache = sector; return sector; } MapSector * Map::getSectorNoGenerate(v2s16 p) { return getSectorNoGenerateNoLock(p); } MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d) { v2s16 p2d(p3d.X, p3d.Z); MapSector * sector = getSectorNoGenerate(p2d); if(sector == NULL) return NULL; MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y); return block; } MapBlock * Map::getBlockNoCreate(v3s16 p3d) { MapBlock *block = getBlockNoCreateNoEx(p3d); if(block == NULL) throw InvalidPositionException(); return block; } bool Map::isNodeUnderground(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreateNoEx(blockpos); return block && block->getIsUnderground(); } bool Map::isValidPosition(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreateNoEx(blockpos); return (block != NULL); } // Returns a CONTENT_IGNORE node if not found MapNode Map::getNode(v3s16 p, bool *is_valid_position) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block == NULL) { if (is_valid_position != NULL) *is_valid_position = false; return {CONTENT_IGNORE}; } v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; bool is_valid_p; MapNode node = block->getNodeNoCheck(relpos, &is_valid_p); if (is_valid_position != NULL) *is_valid_position = is_valid_p; return node; } // throws InvalidPositionException if not found void Map::setNode(v3s16 p, MapNode & n) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreate(blockpos); v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; // Never allow placing CONTENT_IGNORE, it causes problems if(n.getContent() == CONTENT_IGNORE){ bool temp_bool; errorstream<<"Map::setNode(): Not allowing to place CONTENT_IGNORE" <<" while trying to replace \"" <get(block->getNodeNoCheck(relpos, &temp_bool)).name <<"\" at "<setNodeNoCheck(relpos, n); } void Map::addNodeAndUpdate(v3s16 p, MapNode n, std::map &modified_blocks, bool remove_metadata) { // Collect old node for rollback RollbackNode rollback_oldnode(this, p, m_gamedef); // This is needed for updating the lighting MapNode oldnode = getNode(p); // Remove node metadata if (remove_metadata) { removeNodeMetadata(p); } // Set the node on the map // Ignore light (because calling voxalgo::update_lighting_nodes) n.setLight(LIGHTBANK_DAY, 0, m_nodedef); n.setLight(LIGHTBANK_NIGHT, 0, m_nodedef); setNode(p, n); // Update lighting std::vector > oldnodes; oldnodes.emplace_back(p, oldnode); voxalgo::update_lighting_nodes(this, oldnodes, modified_blocks); for (auto &modified_block : modified_blocks) { modified_block.second->expireDayNightDiff(); } // Report for rollback if(m_gamedef->rollback()) { RollbackNode rollback_newnode(this, p, m_gamedef); RollbackAction action; action.setSetNode(p, rollback_oldnode, rollback_newnode); m_gamedef->rollback()->reportAction(action); } /* Add neighboring liquid nodes and this node to transform queue. (it's vital for the node itself to get updated last, if it was removed.) */ for (const v3s16 &dir : g_7dirs) { v3s16 p2 = p + dir; bool is_valid_position; MapNode n2 = getNode(p2, &is_valid_position); if(is_valid_position && (m_nodedef->get(n2).isLiquid() || n2.getContent() == CONTENT_AIR)) m_transforming_liquid.push_back(p2); } } void Map::removeNodeAndUpdate(v3s16 p, std::map &modified_blocks) { addNodeAndUpdate(p, MapNode(CONTENT_AIR), modified_blocks, true); } bool Map::addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata) { MapEditEvent event; event.type = remove_metadata ? MEET_ADDNODE : MEET_SWAPNODE; event.p = p; event.n = n; bool succeeded = true; try{ std::map modified_blocks; addNodeAndUpdate(p, n, modified_blocks, remove_metadata); // Copy modified_blocks to event for (auto &modified_block : modified_blocks) { event.modified_blocks.insert(modified_block.first); } } catch(InvalidPositionException &e){ succeeded = false; } dispatchEvent(event); return succeeded; } bool Map::removeNodeWithEvent(v3s16 p) { MapEditEvent event; event.type = MEET_REMOVENODE; event.p = p; bool succeeded = true; try{ std::map modified_blocks; removeNodeAndUpdate(p, modified_blocks); // Copy modified_blocks to event for (auto &modified_block : modified_blocks) { event.modified_blocks.insert(modified_block.first); } } catch(InvalidPositionException &e){ succeeded = false; } dispatchEvent(event); return succeeded; } struct TimeOrderedMapBlock { MapSector *sect; MapBlock *block; TimeOrderedMapBlock(MapSector *sect, MapBlock *block) : sect(sect), block(block) {} bool operator<(const TimeOrderedMapBlock &b) const { return block->getUsageTimer() < b.block->getUsageTimer(); }; }; /* Updates usage timers */ void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, std::vector *unloaded_blocks) { bool save_before_unloading = (mapType() == MAPTYPE_SERVER); // Profile modified reasons Profiler modprofiler; std::vector sector_deletion_queue; u32 deleted_blocks_count = 0; u32 saved_blocks_count = 0; u32 block_count_all = 0; beginSave(); // If there is no practical limit, we spare creation of mapblock_queue if (max_loaded_blocks == U32_MAX) { for (auto §or_it : m_sectors) { MapSector *sector = sector_it.second; bool all_blocks_deleted = true; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { block->incrementUsageTimer(dtime); if (block->refGet() == 0 && block->getUsageTimer() > unload_timeout) { v3s16 p = block->getPos(); // Save if modified if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) { modprofiler.add(block->getModifiedReasonString(), 1); if (!saveBlock(block)) continue; saved_blocks_count++; } // Delete from memory sector->deleteBlock(block); if (unloaded_blocks) unloaded_blocks->push_back(p); deleted_blocks_count++; } else { all_blocks_deleted = false; block_count_all++; } } if (all_blocks_deleted) { sector_deletion_queue.push_back(sector_it.first); } } } else { std::priority_queue mapblock_queue; for (auto §or_it : m_sectors) { MapSector *sector = sector_it.second; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { block->incrementUsageTimer(dtime); mapblock_queue.push(TimeOrderedMapBlock(sector, block)); } } block_count_all = mapblock_queue.size(); // Delete old blocks, and blocks over the limit from the memory while (!mapblock_queue.empty() && (mapblock_queue.size() > max_loaded_blocks || mapblock_queue.top().block->getUsageTimer() > unload_timeout)) { TimeOrderedMapBlock b = mapblock_queue.top(); mapblock_queue.pop(); MapBlock *block = b.block; if (block->refGet() != 0) continue; v3s16 p = block->getPos(); // Save if modified if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) { modprofiler.add(block->getModifiedReasonString(), 1); if (!saveBlock(block)) continue; saved_blocks_count++; } // Delete from memory b.sect->deleteBlock(block); if (unloaded_blocks) unloaded_blocks->push_back(p); deleted_blocks_count++; block_count_all--; } // Delete empty sectors for (auto §or_it : m_sectors) { if (sector_it.second->empty()) { sector_deletion_queue.push_back(sector_it.first); } } } endSave(); // Finally delete the empty sectors deleteSectors(sector_deletion_queue); if(deleted_blocks_count != 0) { PrintInfo(infostream); // ServerMap/ClientMap: infostream<<"Unloaded "< *unloaded_blocks) { timerUpdate(0.0, -1.0, 0, unloaded_blocks); } void Map::deleteSectors(std::vector §orList) { for (v2s16 j : sectorList) { MapSector *sector = m_sectors[j]; // If sector is in sector cache, remove it from there if(m_sector_cache == sector) m_sector_cache = NULL; // Remove from map and delete m_sectors.erase(j); delete sector; } } void Map::PrintInfo(std::ostream &out) { out<<"Map: "; } #define WATER_DROP_BOOST 4 const static v3s16 liquid_6dirs[6] = { // order: upper before same level before lower v3s16( 0, 1, 0), v3s16( 0, 0, 1), v3s16( 1, 0, 0), v3s16( 0, 0,-1), v3s16(-1, 0, 0), v3s16( 0,-1, 0) }; enum NeighborType : u8 { NEIGHBOR_UPPER, NEIGHBOR_SAME_LEVEL, NEIGHBOR_LOWER }; struct NodeNeighbor { MapNode n; NeighborType t; v3s16 p; NodeNeighbor() : n(CONTENT_AIR), t(NEIGHBOR_SAME_LEVEL) { } NodeNeighbor(const MapNode &node, NeighborType n_type, const v3s16 &pos) : n(node), t(n_type), p(pos) { } }; void Map::transforming_liquid_add(v3s16 p) { m_transforming_liquid.push_back(p); } void Map::transformLiquids(std::map &modified_blocks, ServerEnvironment *env) { u32 loopcount = 0; u32 initial_size = m_transforming_liquid.size(); /*if(initial_size != 0) infostream<<"transformLiquids(): initial_size="< must_reflow; std::vector > changed_nodes; u32 liquid_loop_max = g_settings->getS32("liquid_loop_max"); u32 loop_max = liquid_loop_max; #if 0 /* If liquid_loop_max is not keeping up with the queue size increase * loop_max up to a maximum of liquid_loop_max * dedicated_server_step. */ if (m_transforming_liquid.size() > loop_max * 2) { // "Burst" mode float server_step = g_settin This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "noise.h" #include "nodedef.h" #include "util/string.h" #include "util/container.h" #define MAPGEN_DEFAULT MAPGEN_V7 #define MAPGEN_DEFAULT_NAME "v7" /////////////////// Mapgen flags #define MG_TREES 0x01 // Obsolete. Moved into mgv6 flags #define MG_CAVES 0x02 #define MG_DUNGEONS 0x04 #define MG_FLAT 0x08 // Obsolete. Moved into mgv6 flags #define MG_LIGHT 0x10 #define MG_DECORATIONS 0x20 #define MG_BIOMES 0x40 #define MG_ORES 0x80 typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class Settings; class MMVManip; class NodeDefManager; extern FlagDesc flagdesc_mapgen[]; extern FlagDesc flagdesc_gennotify[]; class Biome; class BiomeGen; struct BiomeParams; class BiomeManager; class EmergeParams; class EmergeManager; class MapBlock; class VoxelManipulator; struct BlockMakeData; class VoxelArea; class Map; enum MapgenObject { MGOBJ_VMANIP, MGOBJ_HEIGHTMAP, MGOBJ_BIOMEMAP, MGOBJ_HEATMAP, MGOBJ_HUMIDMAP, MGOBJ_GENNOTIFY }; enum GenNotifyType { GENNOTIFY_DUNGEON, GENNOTIFY_TEMPLE, GENNOTIFY_CAVE_BEGIN, GENNOTIFY_CAVE_END, GENNOTIFY_LARGECAVE_BEGIN, GENNOTIFY_LARGECAVE_END, GENNOTIFY_DECORATION, NUM_GENNOTIFY_TYPES }; struct GenNotifyEvent { GenNotifyType type; v3s16 pos; u32 id; }; class GenerateNotifier { public: // Use only for temporary Mapgen objects with no map generation! GenerateNotifier() = default; GenerateNotifier(u32 notify_on, const std::set<u32> *notify_on_deco_ids); bool addEvent(GenNotifyType type, v3s16 pos, u32 id=0); void getEvents(std::map<std::string, std::vector<v3s16> > &event_map); void clearEvents(); private: u32 m_notify_on = 0; const std::set<u32> *m_notify_on_deco_ids = nullptr; std::list<GenNotifyEvent> m_notify_events; }; // Order must match the order of 'static MapgenDesc g_reg_mapgens[]' in mapgen.cpp enum MapgenType { MAPGEN_V7, MAPGEN_VALLEYS, MAPGEN_CARPATHIAN, MAPGEN_V5, MAPGEN_FLAT, MAPGEN_FRACTAL, MAPGEN_SINGLENODE, MAPGEN_V6, MAPGEN_INVALID, }; struct MapgenParams { MapgenParams() = default; virtual ~MapgenParams(); MapgenType mgtype = MAPGEN_DEFAULT; s16 chunksize = 5; u64 seed = 0; s16 water_level = 1; s16 mapgen_limit = MAX_MAP_GENERATION_LIMIT; // Flags set in readParams u32 flags = 0; u32 spflags = 0; BiomeParams *bparams = nullptr; s16 mapgen_edge_min = -MAX_MAP_GENERATION_LIMIT; s16 mapgen_edge_max = MAX_MAP_GENERATION_LIMIT; virtual void readParams(const Settings *settings); virtual void writeParams(Settings *settings) const; // Default settings for g_settings such as flags virtual void setDefaultSettings(Settings *settings) {}; s32 getSpawnRangeMax(); private: void calcMapgenEdges(); bool m_mapgen_edges_calculated = false; }; /* Generic interface for map generators. All mapgens must inherit this class. If a feature exposed by a public member pointer is not supported by a certain mapgen, it must be set to NULL. Apart from makeChunk, getGroundLevelAtPoint, and getSpawnLevelAtPoint, all methods can be used by constructing a Mapgen base class and setting the appropriate public members (e.g. vm, ndef, and so on). */ class Mapgen { public: s32 seed = 0; int water_level = 0; int mapgen_limit = 0; u32 flags = 0; bool generating = false; int id = -1; MMVManip *vm = nullptr; const NodeDefManager *ndef = nullptr; u32 blockseed; s16 *heightmap = nullptr; biome_t *biomemap = nullptr; v3s16 csize; BiomeGen *biomegen = nullptr; GenerateNotifier gennotify; Mapgen() = default; Mapgen(int mapgenid, MapgenParams *params, EmergeParams *emerge); virtual ~Mapgen() = default; DISABLE_CLASS_COPY(Mapgen); virtual MapgenType getType() const { return MAPGEN_INVALID; } static u32 getBlockSeed(v3s16 p, s32 seed); static u32 getBlockSeed2(v3s16 p, s32 seed); s16 findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax); s16 findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax); void updateHeightmap(v3s16 nmin, v3s16 nmax); void getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, std::vector<s16> &floors, std::vector<s16> &ceilings); void updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax); void setLighting(u8 light, v3s16 nmin, v3s16 nmax); void lightSpread(VoxelArea &a, std::queue<std::pair<v3s16, u8>> &queue, const v3s16 &p, u8 light); void calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax, bool propagate_shadow = true); void propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow); void spreadLight(const v3s16 &nmin, const v3s16 &nmax); virtual void makeChunk(BlockMakeData *data) {} virtual int getGroundLevelAtPoint(v2s16 p) { return 0; } // getSpawnLevelAtPoint() is a function within each mapgen that returns a // suitable y co-ordinate for player spawn ('suitable' usually meaning // within 16 nodes of water_level). If a suitable spawn level cannot be // found at the specified (X, Z) 'MAX_MAP_GENERATION_LIMIT' is returned to // signify this and to cause Server::findSpawnPos() to try another (X, Z). virtual int getSpawnLevelAtPoint(v2s16 p) { return 0; } // Mapgen management functions static MapgenType getMapgenType(const std::string &mgname); static const char *getMapgenName(MapgenType mgtype); static Mapgen *createMapgen(MapgenType mgtype, MapgenParams *params, EmergeParams *emerge); static MapgenParams *createMapgenParams(MapgenType mgtype); static void getMapgenNames(std::vector<const char *> *mgnames, bool include_hidden); static void setDefaultSettings(Settings *settings); private: // isLiquidHorizontallyFlowable() is a helper function for updateLiquid() // that checks whether there are floodable nodes without liquid beneath // the node at index vi. inline bool isLiquidHorizontallyFlowable(u32 vi, v3s16 em); }; /* MapgenBasic is a Mapgen implementation that handles basic functionality the majority of conventional mapgens will probably want to use, but isn't generic enough to be included as part of the base Mapgen class (such as generating biome terrain over terrain node skeletons, generating caves, dungeons, etc.) Inherit MapgenBasic instead of Mapgen to add this basic functionality to your mapgen without having to reimplement it. Feel free to override any of these methods if you desire different or more advanced behavior. Note that you must still create your own generateTerrain implementation when inheriting MapgenBasic. */ class MapgenBasic : public Mapgen { public: MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerge); virtual ~MapgenBasic(); virtual void generateBiomes(); virtual void dustTopNodes(); virtual void generateCavesNoiseIntersection(s16 max_stone_y); virtual void generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_ymax); virtual bool generateCavernsNoise(s16 max_stone_y); virtual void generateDungeons(s16 max_stone_y); protected: EmergeParams *m_emerge; BiomeManager *m_bmgr; Noise *noise_filler_depth; v3s16 node_min; v3s16 node_max; v3s16 full_node_min; v3s16 full_node_max; content_t c_stone; content_t c_water_source; content_t c_river_water_source; content_t c_lava_source; content_t c_cobble; int ystride; int zstride; int zstride_1d; int zstride_1u1d; u32 spflags; NoiseParams np_cave1; NoiseParams np_cave2; NoiseParams np_cavern; NoiseParams np_dungeons; float cave_width; float cavern_limit; float cavern_taper; float cavern_threshold; int small_cave_num_min; int small_cave_num_max; int large_cave_num_min; int large_cave_num_max; float large_cave_flooded; s16 large_cave_depth; s16 dungeon_ymin; s16 dungeon_ymax; }; ull_bpmax); // Note: we may need this again at some point. #if 0 // Ensure none of the blocks to be generated were marked as // containing CONTENT_IGNORE for (s16 z = blockpos_min.Z; z <= blockpos_max.Z; z++) { for (s16 y = blockpos_min.Y; y <= blockpos_max.Y; y++) { for (s16 x = blockpos_min.X; x <= blockpos_max.X; x++) { core::map::Node *n; n = data->vmanip->m_loaded_blocks.find(v3s16(x, y, z)); if (n == NULL) continue; u8 flags = n->getValue(); flags &= ~VMANIP_BLOCK_CONTAINS_CIGNORE; n->setValue(flags); } } } #endif // Data is ready now. return true; } void ServerMap::finishBlockMake(BlockMakeData *data, std::map *changed_blocks) { v3s16 bpmin = data->blockpos_min; v3s16 bpmax = data->blockpos_max; v3s16 extra_borders(1, 1, 1); bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info; EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax)); /* Blit generated stuff to map NOTE: blitBackAll adds nearly everything to changed_blocks */ data->vmanip->blitBackAll(changed_blocks); EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()=" << changed_blocks->size()); /* Copy transforming liquid information */ while (data->transforming_liquid.size()) { m_transforming_liquid.push_back(data->transforming_liquid.front()); data->transforming_liquid.pop_front(); } for (auto &changed_block : *changed_blocks) { MapBlock *block = changed_block.second; if (!block) continue; /* Update day/night difference cache of the MapBlocks */ block->expireDayNightDiff(); /* Set block as modified */ block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_EXPIRE_DAYNIGHTDIFF); } /* Set central blocks as generated */ for (s16 x = bpmin.X; x <= bpmax.X; x++) for (s16 z = bpmin.Z; z <= bpmax.Z; z++) for (s16 y = bpmin.Y; y <= bpmax.Y; y++) { MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z)); if (!block) continue; block->setGenerated(true); } /* Save changed parts of map NOTE: Will be saved later. */ //save(MOD_STATE_WRITE_AT_UNLOAD); m_chunks_in_progress.erase(bpmin); } MapSector *ServerMap::createSector(v2s16 p2d) { /* Check if it exists already in memory */ MapSector *sector = getSectorNoGenerate(p2d); if (sector) return sector; /* Do not create over max mapgen limit */ const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE; if (p2d.X < -max_limit_bp || p2d.X > max_limit_bp || p2d.Y < -max_limit_bp || p2d.Y > max_limit_bp) throw InvalidPositionException("createSector(): pos. over max mapgen limit"); /* Generate blank sector */ sector = new MapSector(this, p2d, m_gamedef); // Sector position on map in nodes //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; /* Insert to container */ m_sectors[p2d] = sector; return sector; } #if 0 /* This is a quick-hand function for calling makeBlock(). */ MapBlock * ServerMap::generateBlock( v3s16 p, std::map &modified_blocks ) { bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info"); TimeTaker timer("generateBlock"); //MapBlock *block = original_dummy; v2s16 p2d(p.X, p.Z); v2s16 p2d_nodes = p2d * MAP_BLOCKSIZE; /* Do not generate over-limit */ if(blockpos_over_limit(p)) { infostream<makeChunk(&data); //mapgen::make_block(&data); if(enable_mapgen_debug_info == false) t.stop(true); // Hide output } /* Blit data back on map, update lighting, add mobs and whatever this does */ finishBlockMake(&data, modified_blocks); /* Get central block */ MapBlock *block = getBlockNoCreateNoEx(p); #if 0 /* Check result */ if(block) { bool erroneus_content = false; for(s16 z0=0; z0getNode(p); if(n.getContent() == CONTENT_IGNORE) { infostream<<"CONTENT_IGNORE at " <<"("<setNode(v3s16(x0,y0,z0), n); } } } #endif if(enable_mapgen_debug_info == false) timer.stop(true); // Hide output return block; } #endif MapBlock * ServerMap::createBlock(v3s16 p) { /* Do not create over max mapgen limit */ if (blockpos_over_max_limit(p)) throw InvalidPositionException("createBlock(): pos. over max mapgen limit"); v2s16 p2d(p.X, p.Z); s16 block_y = p.Y; /* This will create or load a sector if not found in memory. If block exists on disk, it will be loaded. NOTE: On old save formats, this will be slow, as it generates lighting on blocks for them. */ MapSector *sector; try { sector = createSector(p2d); } catch (InvalidPositionException &e) { infostream<<"createBlock: createSector() failed"<getBlockNoCreateNoEx(block_y); if (block) { if(block->isDummy()) block->unDummify(); return block; } // Create blank block = sector->createBlankBlock(block_y); return block; } MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank) { { MapBlock *block = getBlockNoCreateNoEx(p); if (block && !block->isDummy()) return block; } { MapBlock *block = loadBlock(p); if(block) return block; } if (create_blank) { MapSector *sector = createSector(v2s16(p.X, p.Z)); MapBlock *block = sector->createBlankBlock(p.Y); return block; } return NULL; } MapBlock *ServerMap::getBlockOrEmerge(v3s16 p3d) { MapBlock *block = getBlockNoCreateNoEx(p3d); if (block == NULL) m_emerge->enqueueBlockEmerge(PEER_ID_INEXISTENT, p3d, false); return block; } // N.B. This requires no synchronization, since data will not be modified unless // the VoxelManipulator being updated belongs to the same thread. void ServerMap::updateVManip(v3s16 pos) { Mapgen *mg = m_emerge->getCurrentMapgen(); if (!mg) return; MMVManip *vm = mg->vm; if (!vm) return; if (!vm->m_area.contains(pos)) return; s32 idx = vm->m_area.index(pos); vm->m_data[idx] = getNode(pos); vm->m_flags[idx] &= ~VOXELFLAG_NO_DATA; vm->m_is_dirty = true; } void ServerMap::save(ModifiedState save_level) { if (!m_map_saving_enabled) { warningstream<<"Not saving map, saving disabled."<getBlocks(blocks); for (MapBlock *block : blocks) { block_count_all++; if(block->getModified() >= (u32)save_level) { // Lazy beginSave() if(!save_started) { beginSave(); save_started = true; } modprofiler.add(block->getModifiedReasonString(), 1); saveBlock(block); block_count++; } } } if(save_started) endSave(); /* Only print if something happened or saved whole map */ if(save_level == MOD_STATE_CLEAN || block_count != 0) { infostream << "ServerMap: Written: " << block_count << " blocks" << ", " << block_count_all << " blocks in memory." << std::endl; PrintInfo(infostream); // ServerMap/ClientMap: infostream<<"Blocks modified by: "<increment(end_time - start_time); } void ServerMap::listAllLoadableBlocks(std::vector &dst) { dbase->listAllLoadableBlocks(dst); if (dbase_ro) dbase_ro->listAllLoadableBlocks(dst); } void ServerMap::listAllLoadedBlocks(std::vector &dst) { for (auto §or_it : m_sectors) { MapSector *sector = sector_it.second; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { v3s16 p = block->getPos(); dst.push_back(p); } } } MapDatabase *ServerMap::createDatabase( const std::string &name, const std::string &savedir, Settings &conf) { if (name == "sqlite3") return new MapDatabaseSQLite3(savedir); if (name == "dummy") return new Database_Dummy(); #if USE_LEVELDB if (name == "leveldb") return new Database_LevelDB(savedir); #endif #if USE_REDIS if (name == "redis") return new Database_Redis(conf); #endif #if USE_POSTGRESQL if (name == "postgresql") { std::string connect_string; conf.getNoEx("pgsql_connection", connect_string); return new MapDatabasePostgreSQL(connect_string); } #endif throw BaseException(std::string("Database backend ") + name + " not supported."); } void ServerMap::beginSave() { dbase->beginSave(); } void ServerMap::endSave() { dbase->endSave(); } bool ServerMap::saveBlock(MapBlock *block) { return saveBlock(block, dbase, m_map_compression_level); } bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db, int compression_level) { v3s16 p3d = block->getPos(); // Dummy blocks are not written if (block->isDummy()) { warningstream << "saveBlock: Not writing dummy block " << PP(p3d) << std::endl; return true; } // Format used for writing u8 version = SER_FMT_VER_HIGHEST_WRITE; /* [0] u8 serialization version [1] data */ std::ostringstream o(std::ios_base::binary); o.write((char*) &version, 1); block->serialize(o, version, true, compression_level); bool ret = db->saveBlock(p3d, o.str()); if (ret) { // We just wrote it to the disk so clear modified flag block->resetModified(); } return ret; } void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load) { try { std::istringstream is(*blob, std::ios_base::binary); u8 version = SER_FMT_VER_INVALID; is.read((char*)&version, 1); if(is.fail()) throw SerializationError("ServerMap::loadBlock(): Failed" " to read MapBlock version"); MapBlock *block = NULL; bool created_new = false; block = sector->getBlockNoCreateNoEx(p3d.Y); if(block == NULL) { block = sector->createBlankBlockNoInsert(p3d.Y); created_new = true; } // Read basic data block->deSerialize(is, version, true); // If it's a new block, insert it to the map if (created_new) { sector->insertBlock(block); ReflowScan scanner(this, m_emerge->ndef); scanner.scan(block, &m_transforming_liquid); } /* Save blocks loaded in old format in new format */ //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load) // Only save if asked to; no need to update version if(save_after_load) saveBlock(block); // We just loaded it from, so it's up-to-date. block->resetModified(); } catch(SerializationError &e) { errorstream<<"Invalid block data in database" <<" ("<getBool("ignore_world_load_errors")){ errorstream<<"Ignoring block load error. Duck and cover! " <<"(ignore_world_load_errors)"<loadBlock(blockpos, &ret); if (!ret.empty()) { loadBlock(&ret, blockpos, createSector(p2d), false); } else if (dbase_ro) { dbase_ro->loadBlock(blockpos, &ret); if (!ret.empty()) { loadBlock(&ret, blockpos, createSector(p2d), false); } } else { return NULL; } MapBlock *block = getBlockNoCreateNoEx(blockpos); if (created_new && (block != NULL)) { std::map modified_blocks; // Fix lighting if necessary voxalgo::update_block_border_lighting(this, block, modified_blocks); if (!modified_blocks.empty()) { //Modified lighting, send event MapEditEvent event; event.type = MEET_OTHER; std::map::iterator it; for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it) event.modified_blocks.insert(it->first); dispatchEvent(event); } } return block; } bool ServerMap::deleteBlock(v3s16 blockpos) { if (!dbase->deleteBlock(blockpos)) return false; MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block) { v2s16 p2d(blockpos.X, blockpos.Z); MapSector *sector = getSectorNoGenerate(p2d); if (!sector) return false; sector->deleteBlock(block); } return true; } void ServerMap::PrintInfo(std::ostream &out) { out<<"ServerMap: "; } bool ServerMap::repairBlockLight(v3s16 blockpos, std::map *modified_blocks) { MapBlock *block = emergeBlock(blockpos, false); if (!block || !block->isGenerated()) return false; voxalgo::repair_block_light(this, block, modified_blocks); return true; } MMVManip::MMVManip(Map *map): VoxelManipulator(), m_map(map) { } void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max, bool load_if_inexistent) { TimeTaker timer1("initialEmerge", &emerge_time); // Units of these are MapBlocks v3s16 p_min = blockpos_min; v3s16 p_max = blockpos_max; VoxelArea block_area_nodes (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); u32 size_MB = block_area_nodes.getVolume()*4/1000000; if(size_MB >= 1) { infostream<<"initialEmerge: area: "; block_area_nodes.print(infostream); infostream<<" ("<::iterator n; n = m_loaded_blocks.find(p); if(n != m_loaded_blocks.end()) continue; bool block_data_inexistent = false; { TimeTaker timer2("emerge load", &emerge_load_time); block = m_map->getBlockNoCreateNoEx(p); if (!block || block->isDummy()) block_data_inexistent = true; else block->copyTo(*this); } if(block_data_inexistent) { if (load_if_inexistent && !blockpos_over_max_limit(p)) { ServerMap *svrmap = (ServerMap *)m_map; block = svrmap->emergeBlock(p, false); if (block == NULL) block = svrmap->createBlock(p); block->copyTo(*this); } else { flags |= VMANIP_BLOCK_DATA_INEXIST; /* Mark area inexistent */ VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); // Fill with VOXELFLAG_NO_DATA for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) { s32 i = m_area.index(a.MinEdge.X,y,z); memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE); } } } /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE) { // Mark that block was loaded as blank flags |= VMANIP_BLOCK_CONTAINS_CIGNORE; }*/ m_loaded_blocks[p] = flags; } m_is_dirty = false; } void MMVManip::blitBackAll(std::map *modified_blocks, bool overwrite_generated) { if(m_area.getExtent() == v3s16(0,0,0)) return; /* Copy data of all blocks */ for (auto &loaded_block : m_loaded_blocks) { v3s16 p = loaded_block.first; MapBlock *block = m_map->getBlockNoCreateNoEx(p); bool existed = !(loaded_block.second & VMANIP_BLOCK_DATA_INEXIST); if (!existed || (block == NULL) || (!overwrite_generated && block->isGenerated())) continue; block->copyFrom(*this); block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_VMANIP); if(modified_blocks) (*modified_blocks)[p] = block; } } //END